/**************************************************************************************************************************************************************
DO-FILE TO REPLICATE: Tomic, Ferrer, Prada and Hernández (2025) Winners’ Restraint or Affective Majoritarianism? Elections, Polarization and Political Support
***************************************************************************************************************************************************************/

*+++++++++++++++++++++++++++++++PREAMBLE+++++++++++++++++++++++++++++++++++++* 

************************
* Directory structure
************************
capture: cd ""

global data "00_original_data/"  
global working "01_working_data/"  
global output "02_output/"  
global aux "04_aux/"

************************
* ADO files
************************
// ssc install fre, replace
// ssc install estout, replace 
// ssc install blindschemes, replace 
// ssc install coefplot, replace
// net install dm79.pkg, from(http://www.stata.com/stb/stb56)
// net install dm49.pkg, from(http://www.stata.com/stb/stb39)
// ssc install mmat2tex, replace
// ssc install catplot, replace
// ssc install marhis, replace

******************
* Plot scheme
******************
set scheme plottig

************************
* Load CSES data
************************
use "${data}cses5.dta", clear


************************************************************
*  MERGE WITH ADDITIONAL DATASET (HANDCODED)
* In this dataset we provide government appointment dates that we use to check which respondents were interviewed before and after government appointment
************************************************************

merge m:1 E1006_NAM E1006_UNALPHA2 E5026_3 using "${working}gov_appointment.dta" 
drop _merge

*+++++++++++++++++++++++++++++DATA MANAGEMENT+++++++++++++++++++++++++++++++++++* 

***********************************************
*  FIRST: INDEPENDENT VARIABLES
***********************************************

***********************************************
*  VARIABLE 1: NEW VARIABLE FOR WINNERS AND LOSERS STATUS
***********************************************

*** CREATION OF NEW VARIABLES

* 1) Respondent vote choice in key election in each country
gen respondent_vote_num=.

foreach country in "AU" "CA" "GB" "HU" "IE" "JP" "LT" "NZ" "KR" {
replace respondent_vote_num=E3013_LH_DC if E1006_UNALPHA2=="`country'"
}

foreach country in "AL" "AT" "BE" "CZ" "DK" "DE" "FI" "GR" "IS" "IL" "IT" "LV" "ME" "NL" "NO" "PL" "PT" "RO" "SK" "SE" "CH" {
replace respondent_vote_num=E3013_LH_PL if E1006_UNALPHA2=="`country'"
}

foreach country in "MX" "SV" "TW" "TR" "US" {
replace respondent_vote_num=E3013_PR_1 if E1006_UNALPHA2=="`country'"
}

foreach country in "BR" "CL" "CR" "FR" "PE" "TN" "UY" {
replace respondent_vote_num=E3013_PR_2 if E1006_UNALPHA2=="`country'"
}

	* countries with mixed electoral systems (i.e DC + PL), use alternative vote variable if missing in principle vote variable 

foreach country in "DE" "IT"{
replace respondent_vote_num=E3013_LH_DC if E1006_UNALPHA2=="`country'" & (E3013_LH_PL ==999988 | E3013_LH_PL ==999993 | E3013_LH_PL >= 999997)
}	

foreach country in "HU" "JP" "LT" "NZ" "KR"{
replace respondent_vote_num=E3013_LH_PL if E1006_UNALPHA2=="`country'" & (E3013_LH_DC ==999988 | E3013_LH_DC ==999993 | E3013_LH_DC >= 999997)
}

gen respondent_vote=string(respondent_vote_num, "%06.0f")

	* Generate an indicator for abstainers (for a robustness test)
gen novoter = .
replace novoter = 1 if respondent_vote == "999999"

	* missing cases: refused to answer, abstained in the election
replace respondent_vote="" if respondent_vote=="999988" | respondent_vote=="999993" | respondent_vote=="999997" | respondent_vote=="999998" | respondent_vote=="999999"

	* Gen vote_match =1 if respondend voted for the same party in both the Party List and the District Candidate systems
	** Note: This does not apply to Italy as vote for PL used for both, so DC comes up as missing/abstained even if not   
	** the case

gen vote_match=.

foreach country in "DE" "IT" "HU" "JP" "LT" "NZ" "KR"{
replace vote_match=1 if E3013_LH_PL==E3013_LH_DC & E1006_UNALPHA2=="`country'"	
}

foreach country in "DE" "IT" "HU" "JP" "LT" "NZ" "KR"{
replace vote_match=0 if E3013_LH_PL!=E3013_LH_DC & E1006_UNALPHA2=="`country'"	
}

foreach country in "DE" "IT" "HU" "JP" "LT" "NZ" "KR"{
replace vote_match=. if respondent_vote==""	& E1006_UNALPHA2=="`country'"
}

* 2) Winning party in key election in each country
	* creation of the winning_party variable

gen winning_party_num=.

foreach country in "BR" "CL" "CR" "FR" "MX" "PE" "TN" "UY" "SV" "TW" "TR" "US"{
replace winning_party_num=E5013 if E1006_UNALPHA2=="`country'"
}

foreach country in "AL" "AU" "CA" "CZ" "GB" "HU" "IE" "JP" "LT" "LV" "NZ" "AT" "BE" "DK" "FI" "DE" "GR" "IS" "IL" "ME" "NL" "NO" "PT" "PL" "RO" "SK" "SE"{
replace winning_party_num=E5014 if E1006_UNALPHA2=="`country'"
}

gen winning_party=string(winning_party_num, "%06.0f")

*3) check if respondents answered the survey before/after the Gov appointment day
	*create date of government appointment 
gen gov_day=string(GovermentAppointmentDay, "%02.0f")
gen gov_year=string(GovermentAppointmentYear, "%04.0f")
gen gov_month=substr(GovermentAppointmentMonth, 1, 2)

egen gov_appointment = concat(gov_day gov_month gov_year), punct(/)
gen gov_appoint = date(gov_appointment , "DMY")
format gov_appoint %td
label variable gov_appoint "government appointment date"

drop gov_day gov_year gov_month GovermentAppointmentDay GovermentAppointmentMonth GovermentAppointmentYear gov_appointment

	* Create date of interview
	
gen resp_month = string(E1032, "%02.0f")
gen resp_day = string(E1033, "%02.0f")
egen interview_date = concat(resp_day resp_month E1034), punct(/)
gen inter_date = date(interview_date , "DMY")
format inter_date %td
label variable inter_date "interview date"
	
drop resp_month resp_day interview_date
			
	* Did respondents answer CSES5 questionnaire after the government was appointed? 1 Yes; 0 No

gen respondent_after = 1 if gov_appoint < inter_date
replace respondent_after = 0 if gov_appoint >= inter_date
label variable respondent_after "Respondents answered the CSES5 questionnaire after the government was appointed"

*create new variable for: incumbent_known when the respondents answer the CSES questions
gen incumbent_known=.
replace incumbent_known=1 if E1015>=12
replace incumbent_known=1 if E1015<12 & respondent_after==1
replace incumbent_known=0 if E1015<12 & respondent_after==0

* create new variable SYTEM 
gen system=1 if E1015>=12
replace system=0 if E1015<12
label def system 0"Parliamentary" 1"Presidential"
label val system system

*4) Winners and Losers: E1015 refers to election_type. Values 12 and 20 refer to Presidential systems. We exclude Tunisia because the winning candidate did not belong to any party.

gen winner = 2 if respondent_vote==winning_party & (respondent_after==1 | E1015>=12) & E1006_UNALPHA2!="TN"
replace winner=0 if respondent_vote != winning_party & respondent_vote!="" & (respondent_after==1 | E1015>=12) & E1006_UNALPHA2!="TN"

* Mexico 2018: Presidential system in which AMLO (from Morena) won. But he had formed an electoral aliance/coalition with Labor Party (PT, 484007), and the Social Encounter Party (PES, 484009). Therefore we include the voters from these parties as winners (although we have checked and it seems that there aren't respondents from these parties):

foreach party in "484007" "484009"{
	replace winner=2 if respondent_vote=="`party'" & E1004 == "MEX_2018"
}

* PR systems in which respondents answered the questionnaire after the government was appointed, we need to recode case by case voters of junior coalition partners as winner=1. Australia and Israel are special cases in which we have 2 winners due to a pre-electoral coalition agreement/rotating premiership, respectively. 

* Australia
replace winner=2 if respondent_vote=="036004" & E1006_UNALPHA2=="AU"


*Finland
foreach party in "246004" "246005" "246006" "246007"{
	replace winner=1 if respondent_vote=="`party'" & E1006_UNALPHA2=="FI" & inter_date >= mdy(5, 8, 2019)
}

* Greece 2015
replace winner=1 if respondent_vote=="300007" & E1004=="GRC_2015"

* Israel
replace winner=2 if respondent_vote=="376002" & E1006_UNALPHA2=="IL"

foreach party in "376004" "376005" "376006"{
replace winner=1 if respondent_vote=="`party'" & E1006_UNALPHA2=="IL" 
}

* Slovakia
foreach party in "703003" "703006"{
	replace winner=1 if respondent_vote=="`party'" & E1006_UNALPHA2=="SK"
}

* Montenegro
foreach party in "499007" "499009" "499023" "499006"{
replace winner=1 if respondent_vote=="`party'" & E1006_UNALPHA2=="ME" 
}

* PR systems in which appointment happened after the fieldwork, we code country by country
* Austria
replace winner=2 if respondent_vote == "040001" & E1006_UNALPHA2=="AT"

foreach party in "040002" "040003" "040004" "040005" "040006" "040007" "040008" "040009" "040010" "040011" "040012" "040013"{
replace winner=0 if respondent_vote=="`party'" & E1006_UNALPHA2=="AT" & inter_date < mdy(10, 25, 2017)
}	

foreach party in "040002" "040004" "040005" "040006" "040007" "040008" "040009" "040010" "040011" "040012" "040013"{
replace winner=0 if respondent_vote=="`party'" & E1006_UNALPHA2=="AT" & inter_date >= mdy(10, 25, 2017)
}

replace winner=1 if respondent_vote=="040003" & E1006_UNALPHA2=="AT" & inter_date >= mdy(10, 25, 2017)		

* Canada
replace winner=2 if respondent_vote=="124002" & E1006_UNALPHA2=="CA"

foreach party in "124001" "124003" "124004" "124005" "124006"{
replace winner=0 if respondent_vote=="`party'" & E1006_UNALPHA2=="CA"
}

* Czechia 2017
replace winner=2 if respondent_vote=="203001" & E1004=="CZE_2017"

foreach party in "203002" "203003" "203004" "203005" "203006" "203007" "203008" "203009" "203010" "203011" "203012" "203013" "203014" "203015" "203016" "203017" "203018" "203019" "203020" "203021" "203022" "203023"{
replace winner=0 if respondent_vote=="`party'" & E1004=="CZE_2017"
}

* Czechia 2021
replace winner=2 if respondent_vote=="203101" & E1004=="CZE_2021"

foreach party in "203102" "203104" "203106" "203107" "203199" "203103" "203198" "203105" "203108" "203109" "203110" "203111" "203112" "203113" "203114" "203115" "203116" "203117" "203118" "203119" "203120" "203121" "203122" "203123" "203124" "203125" "203199"{
replace winner=0 if respondent_vote=="`party'" & E1004=="CZE_2021"
}

foreach party in "203196" "203197"{
replace winner=1 if respondent_vote=="`party'" & E1004=="CZE_2021"
}

foreach party in "203103" "203198"{
replace winner=1 if respondent_vote=="`party'" & E1004=="CZE_2021" & inter_date >= mdy(11, 8, 2021)	
}

* Denmark
replace winner=2 if respondent_vote=="208001" & E1006_UNALPHA2=="DK"

foreach party in "208002" "208003" "208004" "208005" "208006" "208007" "208008" "208009" "208010" "208011" "208012" "208013"{
replace winner=0 if respondent_vote=="`party'" & E1006_UNALPHA2=="DK"
}

* Germany 2017
replace winner=2 if respondent_vote=="276001" & E1004=="DEU_2017"

foreach party in "276002" "276003" "276005" "276007" "276008" "276010" "276011" "276012" "276013" "276014" "276015" "276016" "276017" "276018" "276019" "276020" "276021" "276022" "276023" "276024" "276025" "276026" "276027" "276028" "276029"{
replace winner=0 if respondent_vote=="`party'" & E1004=="DEU_2017"
}

foreach party in "276004" "276006"{
replace winner=1 if respondent_vote=="`party'" & E1004=="DEU_2017" & inter_date >= mdy(10, 9, 2017) & inter_date < mdy(11, 20, 2017)
}

foreach party in "276004" "276006"{
replace winner=0 if respondent_vote=="`party'" & E1004=="DEU_2017" & (inter_date < mdy(10, 9, 2017) | inter_date >= mdy(11, 20, 2017))
}

* Germany 2021
replace winner=2 if respondent_vote=="276101" & E1004=="DEU_2021"

foreach party in "276102" "276103" "276104" "276105" "276106" "276107" "276108" "276109" "276110" "276111" "276112" "276113" "276114" "276115" "276116" "276117" "276118" "276119" "276120" "276121" "276122" "276123" "276124" "276125" "276126" "276127" "276128" "276129"{
replace winner=0 if respondent_vote=="`party'" & E1004=="DEU_2021"
}

foreach party in "276103" "276104"{
replace winner=1 if respondent_vote=="`party'" & E1004=="DEU_2021" & inter_date >= mdy(10, 18, 2021)
}

* Greece 2019
replace winner=2 if respondent_vote=="300101" & E1004=="GRC_2019"

foreach party in "300102" "300103" "300104" "300105" "300106" "300107" "300108" "300109" "300110" "300111" "300112" "300113" "300114" "300115" "300116" "300117" "300118" "300119"{
replace winner=0 if respondent_vote=="`party'" & E1004=="GRC_2019"
}

* Hungary
replace winner=2 if respondent_vote=="348001" & E1006_UNALPHA2=="HU"

foreach party in "348002" "348003" "348004" "348005" "348006" "348007" "348008" "348009" "348010" "348011"{
replace winner=0 if respondent_vote=="`party'" & E1006_UNALPHA2=="HU"
}

* Lithuania 2016
replace winner=2 if respondent_vote == "440002" & E1004=="LTU_2016"
replace winner=1 if respondent_vote == "440003" & E1004=="LTU_2016"

foreach party in "440001" "440004" "440005" "440006" "440007" "440008" "440009" "440010" "440011" "440012" "440013" "440014" "440015" "440016" "440017" "440018" "440019" "440020" "440021" "440022"{
replace winner=0 if respondent_vote=="`party'" & E1004=="LTU_2016"
}

* Lithuania 2020
replace winner=2 if respondent_vote == "440101" & E1004=="LTU_2020"

foreach party in "440106" "440105"{
replace winner=1 if respondent_vote =="`party'" & E1004=="LTU_2020"
}

foreach party in "440102" "440103" "440104" "440107" "440108" "440109" "440110" "440111" "440112" "440113" "440114" "440115" "440116" "440117" "440118" "440119" "440120" "440121" "440122"{
replace winner=0 if respondent_vote=="`party'" & E1004=="LTU_2020"
}

* Netherlands
replace winner=2 if respondent_vote == "528001" & E1006_UNALPHA2=="NL"

foreach party in "528002" "528003" "528004" "528005" "528006" "528007" "528008" "528009" "528010" "528011" "528012" "528013" "528014" "528015" "528016" "528017" "528018"{
replace winner=0 if respondent_vote=="`party'" & E1006_UNALPHA2=="NL"
}

* New Zealand (2020)
replace winner=2 if respondent_vote == "554101" & E1006_UNALPHA2=="NZ"
replace winner=1 if respondent_vote == "554102" & E1006_UNALPHA2=="NZ" & inter_date >= mdy(10, 31, 2020)
replace winner=0 if respondent_vote == "554102" & E1006_UNALPHA2=="NZ" & inter_date < mdy(10, 31, 2020)

foreach party in "554103" "554104" "554105" "554106" "554107" "554108" "554109" {
replace winner=0 if respondent_vote=="`party'" & E1006_UNALPHA2=="NZ"
}

* Norway
replace winner=2 if respondent_vote == "578002" & E1006_UNALPHA2=="NO"

foreach party in "578003" "578006"{
	replace winner=1 if respondent_vote=="`party'" & E1006_UNALPHA2=="NO"
}

foreach party in "578001" "578004" "578005" "578007" "578008" "578009"{
	replace winner=0 if respondent_vote=="`party'" & E1006_UNALPHA2=="NO"
}

replace winner=1 if respondent_vote=="578007" & E1006_UNALPHA2=="NO" & inter_date < mdy(9, 28, 2017)

* Poland 
replace winner=2 if respondent_vote == "616001" & E1004=="POL_2019"

foreach party in "616002" "616003" "616004" "616005" "616006" "616007" "616008" "616009" "616010" "616011" "616012"{
replace winner=0 if respondent_vote=="`party'" & E1004=="POL_2019"
}

* Portugal
replace winner=2 if respondent_vote == "620001" & E1006_UNALPHA2=="PT"

foreach party in "620002" "620003" "620004" "620005" "620006" "620007" "620008" "620009" "620010" {
replace winner=0 if respondent_vote=="`party'" & E1006_UNALPHA2=="PT"
}

* Romania 2016
replace winner=2 if respondent_vote=="642001" & E1004=="ROU_2016"

foreach party in "642002" "642003" "642004" "642006" "642007" "642008" "642009" "642010" "642011" "642012" "642013" "642014" "642015" "642016" "642017" "642018"{
replace winner=0 if respondent_vote=="`party'" & E1004=="ROU_2016"
}

foreach party in "642005"{
replace winner=1 if respondent_vote=="`party'" & E1004=="ROU_2016" & inter_date >= mdy(12, 19, 2016)
}

* Tunisia, Presidential system where winning candidate in the second round of Presidential election did not belong the any party
* Tunisia
replace winner=2 if respondent_vote=="788020" & E1006_UNALPHA2=="TN"
replace winner=0 if respondent_vote=="788002" & E1006_UNALPHA2=="TN"

*5) Gen variables with dates for changes in status. The new variable(s) indicate(s) the date in which any change in status for any party took place.
	* change_1
gen change_1=mdy(10, 25, 2017) if E1006_UNALPHA2=="AT"
format change_1 %td

replace change_1=mdy(5, 8, 2019) if E1006_UNALPHA2=="FI"
replace change_1=mdy(10, 9, 2017) if E1004=="DEU_2017"
replace change_1=mdy(10, 18, 2021) if E1004=="DEU_2021"
replace change_1=mdy(10, 31, 2020) if E1006_UNALPHA2=="NZ" & E5026_3==2020
replace change_1=mdy(9, 28, 2017) if E1006_UNALPHA2=="NO"
replace change_1=mdy(11, 8, 2021) if E1004=="CZE_2021"
replace change_1=mdy(12, 19, 2016) if E1004=="ROU_2016"

	* change_2
gen change_2=mdy(11, 20, 2017) if E1006_UNALPHA2=="DE" 
format change_2 %td

*6) Gen status for each country-election.

*default:  
gen status="coded"

*counties excluded beacuase not democratic:
foreach country in "TH" "HK" "IN" "TR" {
	replace status = "undemocratic" if E1006_UNALPHA2=="`country'"
}

*country-election we use as case study:
replace status="case_study" if E1006_UNALPHA2=="NZ" & E1008==2017

*country-elections in which there is no clear winner:
replace status="no_winner" if E1006_UNALPHA2=="BE"
replace status="no_winner" if E1006_UNALPHA2=="IE" 
replace status="no_winner" if E1006_UNALPHA2=="IT"  
replace status="no_winner" if E1006_UNALPHA2=="SE" 
replace status="no_winner" if E1006_UNALPHA2=="CH"
replace status="no_winner" if E1006_UNALPHA2=="IS" & E1008==2016
replace status="no_winner" if E1006_UNALPHA2=="IS" & E1008==2017
replace status="no_winner" if E1006_UNALPHA2=="KR"
replace status="no_winner" if E1006_UNALPHA2=="LV" & E1008==2018
replace status="no_winner" if E1006_UNALPHA2=="NL" & E1008==2021

*Country where CSES 5 made a mistake during fieldwork: Forgot to ask certain questions such as vote choice. Also, we lack interview day (appears as missing for every respondent). We can still use case if looking at winners=2 (although data might not be reliable), but lack information to assign value for winner=1.
replace status="CSES_error" if E1006_UNALPHA2=="FI"

*** Labelling values
label def win 0"Loser" 1"Winner junior coalition" 2"Winner PM or president"
label val winner win

* DROP TUNISIA since winning party is an independent for which there is no data about like dislike or vote share 
drop if E1004 == "TUN_2019"

/*****************************************************************
VARIABLE 2: Size (Vote share) of the party voted for
 
 We use this as a control in the models (see section 3.1 of the paper for a justification of this)
*******************************************************************/

* Following the affective polarization literature (Wagner) lower house vote shares are taken if available; if not, upper house or presidential election vote shares are used.

*** Identifying CSES code of party voted for and matching with dataset party identifier (A, B, C, D...)
gen respondent_vote_CSESletter = "" // Variable that identifies letter assigned in CSES to party voted for

foreach letter in "A" "B" "C" "D" "E" "F" "G" "I"{
		replace respondent_vote_CSESletter = "`letter'" if respondent_vote_num == E5000_`letter' & E5000_`letter' != 999999
}

*** Assigning vote share of party voted for to each respondent (LH)

gen vote_share_party_voted_1 = . // Variable that identifies vote share of party voted for for each respondent. Missing for those who did not vote. Party vote share in the lower house

label var vote_share_party_voted_1 "Vote share party voted for (LH)"

foreach letter in "A" "B" "C" "D" "E" "F" "G" "I"{
	replace vote_share_party_voted_1 = E5001_`letter' if respondent_vote_CSESletter == "`letter'" & E5001_`letter' != 997 & E5001_`letter' != 999
}

* France does not include data on Lower House party size, we use Presidential election instead 
		foreach letter in "A" "B" "C" "D" "E" "F" "G" "I"{
			replace vote_share_party_voted_1 = E5005_`letter' if respondent_vote_CSESletter == "`letter'" & E5005_`letter' != 996 & E5005_`letter' != 997 & E5005_`letter' != 999 & E1006_NAM == "France"
		}	
		
* Salvador does not include data on Lower House party size, we use Presidential election instead 
		foreach letter in "A" "B" "C" "D" "E" "F" "G" "I"{
			replace vote_share_party_voted_1 = E5005_`letter' if respondent_vote_CSESletter == "`letter'" & E5005_`letter' != 996 & E5005_`letter' != 997 & E5005_`letter' != 999 & E1004 == "SLV_2019"
		}	

/**************************************************************************************************************************************************
VARIABLES 3 AND 4: Affective polarization

Opertionalized following Wagner

Here we create the two measures proposed by Wagner: the "spread" measure and the "distance" measure
****************************************************************************************************************************************************/

global letras = "A B C D E F G H I"

* First we again asssign Presidential vote share in France and El Salvador in order to genereate the indeces (due to lack of information on vote in Lower House)
foreach x of global letras{
	replace E5001_`x' = E5005_`x' if E1004 == "FRA_2017" | E1004 == "SLV_2019"
}

********************************************
* Measure 1: Spread of like-dislike scores 
********************************************

* Missing values 
foreach x of global letras{
	replace E5001_`x' = . if E5001_`x' > 100
	replace E3017_`x' = . if E3017_`x' > 10
}

* Normalized (0-1) electoral support for each party (v_p)
foreach var of varlist E5001_*{
	gen `var'_norm = `var'/100
}

* Calculating weighted like dislike score for each party
foreach x of global letras{
	di "`x'"
	gen weighted_like_`x' = E5001_`x'_norm * E3017_`x'
}

* Calculating average weighted like-dislike score for each respodent
egen mean_like = rowtotal(weighted_like_*), missing

* Assigning missing value for respondents who only evaluate one party (wagner computes score if respondents evaluate at least two parties) 
foreach var of varlist E3017_*{
	recode `var' (96/99=0) (0/10=1), gen(`var'_miss)
}

gen sum_non_miss = E3017_A_miss + E3017_B_miss + E3017_C_miss + E3017_D_miss + E3017_E_miss + E3017_F_miss + E3017_G_miss + E3017_H_miss + E3017_I_miss

replace mean_like = . if sum_non_miss < 2

* Calculating the weighted difference of the like-dislike of each party and the average weighted like-dislike score
foreach x of global letras{
	di "`x'"
	gen weighted_difference_`x' = E5001_`x'_norm * (E3017_`x' - mean_like)^2
}

* Generate sum of the weighted difference of the like-dislike of each party and the average weighted like-dislike score
egen sum_spread_nosq = rowtotal(weighted_difference_*) , missing

* Generate the square root of summatory to obtain final score 
gen spread = sqrt(sum_spread_nosq)

* Checks 
bysort E1004: sum spread

* Labelling 
label var spread "Affective polarization (Wagner's spread measure)"


*** drop variables
drop *_miss weighted_difference_* sum_spread_n* *_norm mean_like


************************************************************************
* Measure 2: Mean distance from the most liked party (from Wagner)
************************************************************************
***** New (corrected) code
foreach x of global letras{
	gen E3017_2_`x' = E3017_`x' if E5001_`x'!=.
}

egen max_like = rowmax(E3017_2_*) 

*** ties
foreach x of global letras{
 	gen tie_like_party_`x' = 1 if E3017_`x'==max_like /*Strictly speaking, tie_like_party_`x=1 means that there's no tie because only 1 party has the maximum value*/
}

egen party_tie = rowtotal(tie_like_*)


*** most voted party among the tied parties: need to know variables of party vote share first
foreach x of global letras{
	 gen party_`x'_vs_tie = E5001_`x' if tie_like_party_`x'==1 
} 

egen max_vote = rowmax(party_*_vs_tie)

gen max_like_wagner=""

replace max_like_wagner = "E5001_A" if (abs(E5001_A - max_vote) < 0.001)
replace max_like_wagner = "E5001_B" if (abs(E5001_B - max_vote) < 0.001)
replace max_like_wagner = "E5001_C" if (abs(E5001_C - max_vote) < 0.001)
replace max_like_wagner = "E5001_D" if (abs(E5001_D - max_vote) < 0.001)
replace max_like_wagner = "E5001_E" if (abs(E5001_E - max_vote) < 0.001)
replace max_like_wagner = "E5001_F" if (abs(E5001_F - max_vote) < 0.001)
replace max_like_wagner = "E5001_G" if (abs(E5001_G - max_vote) < 0.001)
replace max_like_wagner = "E5001_H" if (abs(E5001_H - max_vote) < 0.001)
replace max_like_wagner = "E5001_I" if (abs(E5001_I - max_vote) < 0.001)

* next step: new weights
egen total_vote = rowtotal(E5001_*)
gen total_vote_wd = total_vote - max_vote


foreach x of global letras{
    foreach v of varlist E5001_`x'{
	gen weighted_`x'_vs = E5001_`x' / total_vote_wd if max_like_wagner!="`v'"  
	}
}

* Calculating the weighted difference of the like-dislike of each party and the maximum like-dislike score in each case 
foreach x of global letras{
	di "`x'"
	gen weighted_difference2_`x' = weighted_`x'_vs  * (E3017_`x' - max_like)^2
}

* Generate sum of the weighted difference of the like-dislike of each party and the maximum like-dislike score
egen sum_distance_nosq = rowtotal(weighted_difference2_*) , missing

* Generate the square root of summatory to obtain final score 
gen distance = sqrt(sum_distance_nosq)

* Labels 
label var distance "Affective polarization (Wagner's distance measure)"


************************************
*  OTHER VARIABLES: DATA MANAGEMENT
************************************
* STRATEGIC VOTERS
egen most_liked_score = rowmax(E3017_2_*)
gen most_liked_party=""

foreach p in A B C D E F G H I {
    replace most_liked_party = "`p'" if E3017_2_`p' == most_liked_score & party_tie==1
}


* Step 2) Most like party == party voted for?
gen vote_most_liked_party =.
replace vote_most_liked_party=1 if respondent_vote_CSESletter==most_liked_party
replace vote_most_liked_party=0 if respondent_vote_CSESletter!=most_liked_party
replace vote_most_liked_party=. if respondent_vote_CSESletter=="" | most_liked_party==""

tab E1004 vote_most_liked_party

* Step 3) vote share of the party voted for > most like party? we have data at the district level! variables E4004_* and E4004_*_N (nation-wide districts)
foreach p in A B C D E F G H I {
    replace E4004_`p'=. if E4004_`p'> 900     
}

foreach p in A B C D E F G H I {
    replace E4004_`p'_N =. if E4004_`p'_N > 900     
}

*vote share party voted for at the district level
gen vote_share_voted_district=.
foreach p in A B C D E F G H I {
    replace vote_share_voted_district = E4004_`p' if respondent_vote_CSESletter=="`p'"   
}

foreach p in A B C D E F G H I {
    replace vote_share_voted_district = E4004_`p'_N if respondent_vote_CSESletter=="`p'" &  vote_share_voted_district ==. 
}

*vote share most liked party district level
gen vote_share_liked_district=.
foreach p in A B C D E F G H I {
    replace vote_share_liked_district = E4004_`p' if most_liked_party=="`p'"   
}

foreach p in A B C D E F G H I {
    replace vote_share_liked_district = E4004_`p'_N if most_liked_party=="`p'" &  vote_share_liked_district ==. 
}

* Define strategic voter
gen strategic_voter=.
replace strategic_voter=1 if vote_most_liked_party==0 & vote_share_liked_district <= vote_share_voted_district
replace strategic_voter=0 if vote_most_liked_party==1
replace strategic_voter=0 if vote_most_liked_party==0 & vote_share_liked_district > vote_share_voted_district

* Dropping variables that are no longer needed
drop *_like_* max_like *_like *_difference2_* sum_distance_nosq 
drop max_vote total_vote total_vote_wd party_tie party_*_vs_tie 
drop E3017_2_* weighted_*_vs

* Dichotomous winner variable 
gen winner_bi = winner
recode winner_bi (2=1)
label def w 0"Loser" 1"Winner"
label val winner_bi w

* Variable including winners, losers and nonvoters:
gen winner_3 = .
replace winner_3 = 0 if novoter == 1
replace winner_3 = 1 if winner_bi == 0
replace winner_3 = 2 if winner_bi == 1

label def w3 0"Non-voter" 1"Loser" 2"Winner"
label val winner_3 w3

* Define strategic winner
gen winner_strategic = .
label var winner_strategic "Winner"
replace winner_strategic = 1 if winner_bi==0 & (strategic_voter==0 | strategic_voter==1)
replace winner_strategic = 2 if winner_bi==1 & strategic_voter==0
replace winner_strategic = 0 if winner_bi==1 & strategic_voter==1

label def strategic 0"Strategic winner" 1"Loser" 2"Winner"
label val winner_strategic strategic	

* Timing of survey (days from election) with respect to the election 
gen days_since_election = .

replace days_since_election = E1035_1 if E1035_2 == 9996 // We assign the day for those countries/elections that do not have a second round

replace days_since_election = E1035_2 if days_since_election == . // We take time from the second round for those countries that hold a second round. The rationale for this would be that these are usually the key elections that determine W/L status

replace days_since_election = . if E1035_1 == 9995 | E1035_1 == 9999 

label var days_since_election "Days from election to interview"
 
* Numerical variable for country fixed-effects
encode E1006_NAM, gen(cntrynum)

* Numerical variable for country-election fixed effects 
encode E1004, gen(cntry_election_num)

* Age 
gen age = E2001_A 

recode age (9997/9999 = .)

* Gender 
recode E2002 (3/9=.)

* Education 
recode E2003 (96/99=.)

* Ideological extremity
gen extremity = abs(5-E3020)

recode extremity (90/94 = .)

* Party closseness
gen party_close = E3024_4
recode party_close (7/8=.) (1=3) (3=1) (9=0)

* Other controls
recode E2008 E3003 E3001 (7/9=.)
recode E3020 (95/99 = .) 

***********************
* DEPENDENT VARIABLES
***********************

* DV (0): Satisfaction with democracy (SWD)
replace E3023=. if E3023>=8
gen SWD = E3023
recode SWD 5=1 4 =2 6=3 2=4 1=5
replace SWD=. if SWD>=7
label def satisfaction 1"Not at all satisfied" 2"Not very satisfied" 3"Neither satisfaction nor dissatisfied" 4"Fairly satisfied" 5"Very satisfied"
label val SWD satisfaction

* DV (1): will of the majority. Values 7 and above are missing, so:
gen majority_will = E3005_2 if E3005_2<7

	*Reverse the scale 
replace majority_will = 6 - majority_will

	* Labels
label var majority_will "The will of the majority should always prevail, even over the rights of minorities."
label def likert_rev 1"Strongly disagree" 2"Somewhat disagree" 3"Neither agree nor disagree" 4"Somewhat agree" 5"Strongly agree" 
label val majority_will likert_rev

* DV (3): Strong leader who bends the rules 
gen strong_leader = E3004_5 if E3004_5<7
replace strong_leader = 6 - strong_leader
label val strong_leader likert_rev

* Labels 
label var SWD "Satisfaction with democracy"
label var majority_will "Majoritarianism vs Minorities"
label var strong_leader "Strong leader bends rules"
label var winner_bi "Winner"
label var age "Age"
label var E2002 "Female"
label var E2003 "Education"
label var extremity "Ideological extremity"
label var vote_share_party_voted_1 "Vote share party voted"
label var distance "Affective polarization"
label var E3020 "Ideology"
label var E3003 "I. Efficacy"
label var E3001 "Political interest"
label def sex 1"Male" 2"Female"
label val E2002 sex
 
*+++++++++++++++++++++++++++++++DESCRIPTIVES+++++++++++++++++++++++++++++++++++++* 

******************
* Dropping cases
******************

* Drop cases not coded 
fre status 

tab E1004 if status == "coded"
return list 

tab E1006_NAM if status == "coded" 
return list

drop if status != "coded"

* Drop cases that did not ask our dependent variables 
gen incomplete = 0
levelsof cntry_election_num, local(levels)
foreach x of local levels{
	foreach var of varlist SWD majority_will strong_leader{
		quietly: tab `var' if cntry_election_num == `x'
		if `r(N)' == 0{
			replace incomplete = 1 if cntry_election_num == `x'
		}
	}
}

drop if incomplete == 1

 
*+++++++++++++++++++++++++++++++++ ANALYSIS STUDY 1 +++++++++++++++++++++++++++++++++++++++* 

**********************
* FIGURE B1 APPENDIX: DISTRIBUTION OUTCOME VARIABLES
**********************
**** Show the descriptives for the sample that we analyse (by considering those 
   * without missing data in the variables that we include in the regressions):

* Majoritarianism
preserve
contract majority_will if winner_bi !=. & age != . & E2002 != . & E2003 != . & extremity != . & E3001 != .
rename majority_will response
rename _freq majority_will
tempfile m
save `m'
restore

* Strong leader
preserve
contract strong_leader if winner_bi !=. & age != . & E2002 != . & E2003 != . & extremity != . & E3001 != .
rename strong_leader response
rename _freq strong_leader
tempfile s
save `s'
restore

* Satisfaction with democracy
preserve
contract SWD if winner_bi !=. & age != . & E2002 != . & E2003 != . & extremity != . & E3001 != .
rename SWD response
rename _freq SWD
tempfile d
save `d'
restore

preserve
use `m', clear
merge 1:1 response using `s', nogenerate
merge 1:1 response using `d', nogenerate

graph bar majority_will strong_leader SWD, ///
    over(response, label(angle(0)) relabel(1 "1" 2 "2" 3 "3" 4 "4" 5 "5")) ///
    bar(1, color(red)) bar(2, color(green)) bar(3, color(blue)) ///
    legend(pos(6) row(2) label(1 "Majoritarianism vs minority rights") ///
           label(2 "Strong leader above law") ///
           label(3 "Satisfaction with democracy")) ///
    ytitle("Frequency")
	
	graph export "${output}Figure_B1.pdf", replace
	
restore	 


*********************
* TABLE B1 APPENDIX: PAIRWISE CORRELATIONS OUTCOME VARIABLES
********************
pwcorr SWD majority_will strong_leader if winner_bi !=. & age != . & E2002 != . & E2003 != . & extremity != . & E3001 != ., sig

quietly estpost corr SWD majority_will strong_leader if winner_bi !=. & age != . & E2002 != . & E2003 != . & extremity != . & E3001 != ., matrix
esttab . using "${output}Table_B1.tex", replace b(3) star(* 0.05 ** 0.01) unstack nonum nomtitle not noobs ///
label compress eqlabels(SWD Majoritarianism Leader, lhs("Variables"))

	
*************************************
* FIGURE 1 PAPER: Winner-loser gap in satisfaction with democracy and support for norms of democratic restraint and consent
*************************************
* Without controlling for party size
foreach var of varlist SWD majority_will strong_leader{
	reg `var' i.winner_bi age i.E2002 E2003 extremity E3001 i.cntry_election_num
	est store M_`var'_noc
	estadd local ctryRI "\Checkmark"
	margins winner_bi, level(99)
	local point_winner_`var' = r(table)["b",2]
	local point_loser_`var' = r(table)["b",1]
	local ll99_winner_`var' = r(table)["ll",2]
	local ul99_winner_`var'  = r(table)["ul",2]
	local ll99_loser_`var' = r(table)["ll",1]
	local ul99_loser_`var'  = r(table)["ul",1]
	quietly: margins winner_bi, level(95)
	local ll95_winner_`var' = r(table)["ll",2]
	local ul95_winner_`var'  = r(table)["ul",2]
	local ll95_loser_`var' = r(table)["ll",1]
	local ul95_loser_`var'  = r(table)["ul",1]
	
}

* Plot elements
matrix point_winners_noc = `point_winner_SWD', `point_winner_majority_will', `point_winner_strong_leader'
matrix point_losers_noc = `point_loser_SWD', `point_loser_majority_will', `point_loser_strong_leader'

matrix ci_SWD_winner = `ll99_winner_SWD' \ `ul99_winner_SWD' \ `ll95_winner_SWD' \ `ul95_winner_SWD'
matrix ci_majority_will_winner = `ll99_winner_majority_will' \ `ul99_winner_majority_will' \ `ll95_winner_majority_will' \ `ul95_winner_majority_will'
matrix ci_strong_leader_winner = `ll99_winner_strong_leader' \ `ul99_winner_strong_leader' \ `ll95_winner_strong_leader' \ `ul95_winner_strong_leader'

matrix ci_SWD_loser = `ll99_loser_SWD' \ `ul99_loser_SWD' \ `ll95_loser_SWD' \ `ul95_loser_SWD'
matrix ci_majority_will_loser = `ll99_loser_majority_will' \ `ul99_loser_majority_will' \ `ll95_loser_majority_will' \ `ul95_loser_majority_will'
matrix ci_strong_leader_loser = `ll99_loser_strong_leader' \ `ul99_loser_strong_leader' \ `ll95_loser_strong_leader' \ `ul95_loser_strong_leader'

matrix ci_winner_noc = ci_SWD_winner, ci_majority_will_winner, ci_strong_leader_winner
matrix ci_loser_noc = ci_SWD_loser, ci_majority_will_loser, ci_strong_leader_loser

* Controlling for party size 
foreach var of varlist SWD majority_will strong_leader{
	reg `var' i.winner_bi vote_share_party_voted_1 age i.E2002 E2003 extremity E3001 i.cntry_election_num
	est store M_`var'
	estadd local ctryRI "\Checkmark"
	margins winner_bi, level(99)
	local point_winner_`var' = r(table)["b",2]
	local point_loser_`var' = r(table)["b",1]
	local ll99_winner_`var' = r(table)["ll",2]
	local ul99_winner_`var'  = r(table)["ul",2]
	local ll99_loser_`var' = r(table)["ll",1]
	local ul99_loser_`var'  = r(table)["ul",1]
	quietly: margins winner_bi, level(95)
	local ll95_winner_`var' = r(table)["ll",2]
	local ul95_winner_`var'  = r(table)["ul",2]
	local ll95_loser_`var' = r(table)["ll",1]
	local ul95_loser_`var'  = r(table)["ul",1]
	
}

matrix point_winners_con = `point_winner_SWD', `point_winner_majority_will', `point_winner_strong_leader'
matrix point_losers_con = `point_loser_SWD', `point_loser_majority_will', `point_loser_strong_leader'

matrix ci_SWD_winner = `ll99_winner_SWD' \ `ul99_winner_SWD' \ `ll95_winner_SWD' \ `ul95_winner_SWD'
matrix ci_majority_will_winner = `ll99_winner_majority_will' \ `ul99_winner_majority_will' \ `ll95_winner_majority_will' \ `ul95_winner_majority_will'
matrix ci_strong_leader_winner = `ll99_winner_strong_leader' \ `ul99_winner_strong_leader' \ `ll95_winner_strong_leader' \ `ul95_winner_strong_leader'

matrix ci_SWD_loser = `ll99_loser_SWD' \ `ul99_loser_SWD' \ `ll95_loser_SWD' \ `ul95_loser_SWD'
matrix ci_majority_will_loser = `ll99_loser_majority_will' \ `ul99_loser_majority_will' \ `ll95_loser_majority_will' \ `ul95_loser_majority_will'
matrix ci_strong_leader_loser = `ll99_loser_strong_leader' \ `ul99_loser_strong_leader' \ `ll95_loser_strong_leader' \ `ul95_loser_strong_leader'

matrix ci_winner_con = ci_SWD_winner, ci_majority_will_winner, ci_strong_leader_winner
matrix ci_loser_con = ci_SWD_loser, ci_majority_will_loser, ci_strong_leader_loser

* Generating plot 
matrix colnames point_winners_noc = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames point_losers_noc = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames point_winners_con = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames point_losers_con = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"

coefplot	(matrix(point_winners_noc), msymbol(S) label("Winners no party size control")  ci((ci_winner_noc[1] ci_winner_noc[2]) (ci_winner_noc[3] ci_winner_noc[4]))) 	///
			(matrix(point_losers_noc), label("Losers no party size control")  ci((ci_loser_noc[1] ci_loser_noc[2]) (ci_loser_noc[3] ci_loser_noc[4])))	///
			(matrix(point_winners_con), msymbol(S) label("Winners controlling party size")  ci((ci_winner_con[1] ci_winner_con[2]) (ci_winner_con[3] ci_winner_con[4])))	///
			(matrix(point_losers_con), label("Losers controlling party size")  ci((ci_loser_con[1] ci_loser_con[2]) (ci_loser_con[3] ci_loser_con[4]))),	///			
			coeflabels(,wrap(15)) xlabel(2.6(.2)3.6) ///
			mlabel format(%9.3g) mlabposition(12) mlabgap(*1.5) mlabsize(vsmall)

	graph export "${output}Figure_1.pdf", replace

*******************
**** Summary table - TABLE B2 appendix
*******************
esttab 				M_SWD_noc M_SWD M_majority_will_noc M_majority_will ///
					M_strong_leader_noc M_strong_leader ///			
					using "${output}Table_B2.tex", ///
					b(2) se(2) r2 star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					drop(*.cntry_election_num) ///
					mtitles("SWD" "SWD" "Majority" "Majority" "Leader" "Leader") ///
					scalars("ctryRI Country-election fixed-effects") nogap


****************
***** FIGURE B2: Marginal effect of being a winner without controlling for party size
****************

foreach var of varlist SWD majority_will strong_leader{
	reg `var' i.winner_bi age i.E2002 E2003 extremity E3001 i.cntry_election_num
	est store M_`var'_noc
	estadd local ctryRI "\Checkmark"
	margins, dydx(winner_bi) level(95)
	local point_winner_`var' = r(table)["b",2]
	local point_loser_`var' = r(table)["b",1]
	local ll95_winner_`var' = r(table)["ll",2]
	local ul95_winner_`var'  = r(table)["ul",2]
	local ll95_loser_`var' = r(table)["ll",1]
	local ul95_loser_`var'  = r(table)["ul",1]
}

* Plot elements
matrix point_winners_noc = `point_winner_SWD', `point_winner_majority_will', `point_winner_strong_leader'

matrix ci_SWD_winner = `ll95_winner_SWD' \ `ul95_winner_SWD'
matrix ci_majority_will_winner = `ll95_winner_majority_will' \ `ul95_winner_majority_will'
matrix ci_strong_leader_winner = `ll95_winner_strong_leader' \ `ul95_winner_strong_leader'

matrix ci_winner_noc = ci_SWD_winner, ci_majority_will_winner, ci_strong_leader_winner


* Controlling for party size 
foreach var of varlist SWD majority_will strong_leader{
	reg `var' i.winner_bi vote_share_party_voted_1 age i.E2002 E2003 extremity E3001 i.cntry_election_num
	est store M_`var'
	estadd local ctryRI "\Checkmark"
	quietly: margins, dydx(winner_bi) level(95)
	local point_winner_`var' = r(table)["b",2]
	local point_loser_`var' = r(table)["b",1]
	local ll95_winner_`var' = r(table)["ll",2]
	local ul95_winner_`var'  = r(table)["ul",2]
	local ll95_loser_`var' = r(table)["ll",1]
	local ul95_loser_`var'  = r(table)["ul",1]
}

matrix point_winners_con = `point_winner_SWD', `point_winner_majority_will', `point_winner_strong_leader'

matrix ci_SWD_winner = `ll95_winner_SWD' \ `ul95_winner_SWD'
matrix ci_majority_will_winner = `ll95_winner_majority_will' \ `ul95_winner_majority_will'
matrix ci_strong_leader_winner = `ll95_winner_strong_leader' \ `ul95_winner_strong_leader'

matrix ci_winner_con = ci_SWD_winner, ci_majority_will_winner, ci_strong_leader_winner


* Generating plot 
matrix colnames point_winners_noc = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames point_winners_con = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"

coefplot	(matrix(point_winners_noc), msymbol(S) label("No party size control")  ci((ci_winner_noc[1] ci_winner_noc[2]))) 	///
			(matrix(point_winners_con), msymbol(S) label("Controlling party size")  ci((ci_winner_con[1] ci_winner_con[2]))),	///			
			coeflabels(,wrap(15)) xlabel(-0.4(.2)0.4) xline(0, lcol(red) lpat(solid)) ///
			mlabel format(%9.3g) mlabposition(12) mlabgap(*1.5) mlabsize(vsmall)					
					
	graph export "${output}Figure_B2.pdf", replace 		

*************** 
**** FIGURE B3: Relationship between size (vote share) party voted for and political support
***************

foreach var of varlist SWD majority_will strong_leader{
	reg `var' i.winner_bi vote_share_party_voted_1 age i.E2002 E2003 extremity E3001 i.cntry_election_num
	marhis vote_share_party_voted_1
	graph save "${aux}`var'_psize.gph", replace
}

graph combine 	"${aux}SWD_psize.gph"	///
				"${aux}majority_will_psize.gph"	///
				"${aux}strong_leader_psize.gph", ycommon 
				
	graph export "${output}Figure_B3.pdf", replace 

	
					
*********************************************************
* FIGURE 2 PAPER: Satisfaction with democracy and support for norms of democratic restraint and consent as a function of winner and loser status and affective polarization
*********************************************************

foreach var of varlist SWD majority_will strong_leader{
	reg `var' i.winner_bi##c.distance vote_share_party_voted_1 extremity age i.E2002 E2003 E3001 i.cntry_election_num
	est store M_`var'
	estadd local ctryRI "\Checkmark"
	local pvalue: di %4.3f el(r(table),4,5)
	margins winner_bi, at(distance =(0(1)10))
	local label : variable label `var'
	marginsplot, recast(scatter) ti("`label'") plotopts(msymbol(o))	///
	legend(order(1 "Loser" 2 "Winner") position(6) row(1) size(small)) ///
	note("p-value product term = `pvalue'", size(vsmall)) ///
	addplot(hist distance,	///
	yaxis(2) yscale(axis(2) alt) color(%15) ytitle("", axis(2))  ylabel(none, axis(2)) ///
	legend(off)) 
	graph save "${aux}APO_predicted_`var'", replace 
	
	margins r.winner_bi, at(distance =(0(1)10))
	marginsplot, recast(scatter) ti("`var'") ytitle("Winner loser gap") yline(0, lp(solid) lcol(red)) ylabel(-.2(.2)1) ti("`label'")
	graph save "${aux}APO_diff_`var'", replace
}

grc1leg  	"${aux}APO_predicted_SWD.gph"	///
				"${aux}APO_predicted_majority_will.gph"	///
				"${aux}APO_predicted_strong_leader.gph", ycommon legendfrom("${aux}APO_predicted_SWD.gph") 
				
graph export "${output}Figure_2.pdf", replace
	
************
* Figure B5: Differences in political support among winners and losers as a function of affective polarization
************
graph combine 	"${aux}APO_diff_SWD.gph"	///
				"${aux}APO_diff_majority_will.gph"	///
				"${aux}APO_diff_strong_leader.gph"	///, ycommon 
				
graph export "${output}Figure_B5.pdf", replace 	

***********
* Figure B4: Replicates Figure 2, but without controlling for party size
***********

foreach var of varlist SWD majority_will strong_leader{
	reg `var' i.winner_bi##c.distance extremity age i.E2002 E2003 E3001 i.cntry_election_num
	est store M_`var'_noparsize
	estadd local ctryRI "\Checkmark"
	
	local pvalue: di %4.3f el(r(table),4,5)
	margins winner_bi, at(distance =(0(1)10))
	local label : variable label `var'
	marginsplot, recast(scatter) ti("`label'") plotopts(msymbol(o))	///
	legend(order(1 "Loser" 2 "Winner") position(6) row(1) size(small)) ///
	note("p-value product term = `pvalue'", size(vsmall)) ///
	addplot(hist distance,	///
	yaxis(2) yscale(axis(2) alt) color(%15) ytitle("", axis(2))  ylabel(none, axis(2)) ///
	legend(off)) 
	graph save "${aux}APO_predicted_`var'_nopar", replace 
	
}

grc1leg  	"${aux}APO_predicted_SWD_nopar.gph"	///
				"${aux}APO_predicted_majority_will_nopar.gph"	///
				"${aux}APO_predicted_strong_leader_nopar.gph", ycommon  //
				
graph export "${output}Figure_B4.pdf", replace	
			
************************************								
* Summary table - TABLE B3 appendix
************************************

esttab 				M_SWD M_SWD_noparsize M_majority_will M_majority_will_noparsize M_strong_leader M_strong_leader_noparsize ///			
					using "${output}Table_B3.tex", ///
					b(2) se(2) r2 star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					drop(*.cntry_election_num) ///
					mtitles("SWD" "SWD" "Majority" "Majority" "Leader" "Leader") ///
					scalars("ctryRI Country-election fixed-effects") nogap

					
******************************************************************************************
* SPREAD MEASURE OF AFFECTIVE POLARIZATION: FIGURES B5 and B6, and TABLE B4
******************************************************************************************

foreach var of varlist SWD majority_will strong_leader{
	reg `var' i.winner_bi##c.spread vote_share_party_voted_1 extremity age i.E2002 E2003 E3001 i.cntry_election_num
	est store M_`var'
	estadd local ctryRI "\Checkmark"
	local pvalue: di %4.3f el(r(table),4,5)
	margins winner_bi, at(spread =(0(1)5))
	local label : variable label `var'
	marginsplot, recast(scatter) ti("`label'") ///
	note("p-value product term = `pvalue'", size(vsmall))
	graph save "${aux}SAPO_predicted_`var'", replace 
	margins r.winner_bi, at(spread =(0(1)5))
	marginsplot, recast(scatter) ti("`var'") ytitle("Winner loser gap") yline(0, lp(solid) lcol(red)) ylabel(-.2(.2)1) ti("`label'")
	graph save "${aux}SAPO_diff_`var'", replace
}

************
* FIGURE B6: Spread. SWD and support for norms of restraint and consent as a function of the alternative measure of affective polarization (spread)
************ 

grc1leg2  	"${aux}SAPO_predicted_SWD.gph"	///
				"${aux}SAPO_predicted_majority_will.gph"	///
				"${aux}SAPO_predicted_strong_leader.gph", ycommon lcols(2)
				
graph export "${output}Figure_B6.pdf", replace 

************
* FIGURE B7: Differences in political support among winners and losers as a function of affective polarization (spread index)
************
graph combine 	"${aux}SAPO_diff_SWD.gph"	///
				"${aux}SAPO_diff_majority_will.gph"	///
				"${aux}SAPO_diff_strong_leader.gph"	, ycommon 
				
graph export "${output}Figure_B7.pdf", replace 

******************
* Summary table B4: impact of winning and losing on political support moderated by affective polarization spread index
******************
esttab 				M_SWD M_majority_will M_strong_leader ///			
					using "${output}Table_B4.tex", ///
					b(2) se(2) r2 star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					drop(*.cntry_election_num) ///
					mtitles("SWD" "Majority" "Leader") ///
					scalars("ctryRI Country-election fixed-effects") nogap

					
******************************************************************************************
**** ROBUSTNESS CHECKS STUDY 1: social desirability, interview mode
******************************************************************************************					

* Identifying country-elections that conducted interviews with different modes 
gen mixed_mode = 0 

levelsof cntry_election_num, local(levels)
foreach x of local levels{
	tab E1025_1 if cntry_election_num == `x'
	if `r(r)' > 1{
		replace mixed_mode = 1 if cntry_election_num == `x'
	}
	else{
	}
}

tab cntry_election_num if mixed_mode == 1
replace mixed_mode = 0 if cntry_election_num == 30

* Coding private and public modes 
tab E1025_1 if mixed_mode == 1

recode E1025_1 (1/2=1) (6=1) (3=1) (4/5=0), gen(mode) 

tab E1025_1 mode 

label def mode 0"Private" 1"Face to face or phone" 
label val mode mode

***********
*FIGURE B8: Outcome variables as a function of interview mode
*********** 
matrix point_face = J(1,3,.)
matrix point_private = J(1,3,.)
matrix CI_face = J(4,3,.)
matrix CI_private = J(4,3,.)

local x 0
foreach var of varlist SWD majority_will strong_leader{
	local ++ x
	reg `var ' i.mode age E2002 E2003 E3020 E3003 E3001 i.cntry_election_num if mixed_mode == 1
	est store M_`var'
	estadd local ctryRI "\Checkmark"
	margins mode
	matrix point_face[1,`x'] = r(table)[1,2]
	matrix point_private[1,`x'] = r(table)[1,1]
	matrix CI_face[1,`x'] = r(table)[5..6,2]
	matrix CI_private[1,`x'] = r(table)[5..6,1]
	margins mode, level(99)
	matrix CI_face[3,`x'] = r(table)[5..6,2]
	matrix CI_private[3,`x'] = r(table)[5..6,1]
}


foreach x in face private{
	matrix colnames point_`x' = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
	matrix colnames CI_`x' = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
}

coefplot	(matrix(point_face), label("Face to face or phone")  ci((CI_face[3] CI_face[4]) (CI_face[1] CI_face[2]))) 	///
			(matrix(point_private), label("Private")  ci((CI_private[3] CI_private[4]) (CI_private[1] CI_private[2]))),	///
			coeflabels(,wrap(15)) ///
			mlabel format(%9.3g) mlabposition(12) mlabgap(*1.5) mlabsize(vsmall)
			
graph export "${output}Figure_B8.pdf", replace 

************
* FIGURE B9: Analysis of W/L patters as a function of mode of data collection
************
foreach var of varlist SWD majority_will strong_leader{
	reg `var ' i.winner_bi##i.mode age E2002 E2003 E3020 E3003 E3001 i.cntry_election_num if mixed_mode == 1
	margins winner_bi, at(mode=(0 1))
}

* Plotting the results
matrix point_losers_face = J(1,3,.)
matrix point_losers_private = J(1,3,.)
matrix point_winners_face = J(1,3,.)
matrix point_winners_private = J(1,3,.)
matrix CI_losers_face = J(4,3,.)
matrix CI_losers_private = J(4,3,.)
matrix CI_winners_face = J(4,3,.)
matrix CI_winners_private = J(4,3,.)

local x 0
foreach var of varlist SWD majority_will strong_leader{
	local ++ x
	reg `var ' i.winner_bi##i.mode age E2002 E2003 E3020 E3003 E3001 i.cntry_election_num if mixed_mode == 1
	est store M_`var'_inter
	estadd local ctryRI "\Checkmark"
	margins winner_bi, at(mode=(0 1))
	matrix point_losers_face[1,`x'] = r(table)[1,3]
	matrix point_losers_private[1,`x'] = r(table)[1,1]
	matrix point_winners_face[1,`x'] = r(table)[1,4]
	matrix point_winners_private[1,`x'] = r(table)[1,2]
	matrix CI_losers_face[1,`x'] = r(table)[5..6,3]
	matrix CI_losers_private[1,`x'] = r(table)[5..6,1]
	matrix CI_winners_face[1,`x'] = r(table)[5..6,4]
	matrix CI_winners_private[1,`x'] = r(table)[5..6,2]
	margins winner_bi, at(mode=(0 1)) level(99)
	matrix CI_losers_face[3,`x'] = r(table)[5..6,3]
	matrix CI_losers_private[3,`x'] = r(table)[5..6,1]
	matrix CI_winners_face[3,`x'] = r(table)[5..6,4]
	matrix CI_winners_private[3,`x'] = r(table)[5..6,2]
}

foreach x in losers_face losers_private winners_face winners_private{
	matrix colnames point_`x' = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
	matrix colnames CI_`x' = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
}

coefplot	(matrix(point_winners_face), label("Winners face to face or phone")  ci((CI_winners_face[3] CI_winners_face[4]) (CI_winners_face[1] CI_winners_face[2])))	///
			(matrix(point_winners_private), label("Winners private")  ci((CI_winners_private[3] CI_winners_private[4]) (CI_winners_private[1] CI_winners_private[2])))	///		
			(matrix(point_losers_face), label("Losers face to face or phone")  ci((CI_losers_face[3] CI_losers_face[4]) (CI_losers_face[1] CI_losers_face[2]))) 	///
			(matrix(point_losers_private), label("Losers private")  ci((CI_losers_private[3] CI_losers_private[4]) (CI_losers_private[1] CI_losers_private[2]))),	///
			coeflabels(,wrap(15)) ///
			mlabel format(%9.3g) mlabposition(12) mlabgap(*1.5) mlabsize(vsmall)

graph export "${output}Figure_B9.pdf", replace 

*******************
* Summary table B5: social desirability, winners and losers and political support
*******************
esttab 				M_SWD M_majority_will M_strong_leader ///			
					M_SWD_inter M_majority_will_inter M_strong_leader_inter ///
					using "${output}Table_B5.tex", ///
					b(2) se(2) r2 star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					drop(*.cntry_election_num) ///
					mtitles("SWD" "SWD" "Majority" "Majority"  "Leader" "Leader") ///
					scalars("ctryRI Country-election fixed-effects") nogap
					

****************
* Analysis of Non-voters
****************
* Without controlling for party size
foreach var of varlist SWD majority_will strong_leader{
	reg `var' i.winner_3 age i.E2002 E2003 extremity E3001 i.cntry_election_num
	est store M_`var'_noc
	estadd local ctryRI "\Checkmark"
	
	margins winner_3, level(99)
	local point_winner_`var' = r(table)["b",3]
	local point_loser_`var' = r(table)["b",2]
	local point_nonvoter_`var' = r(table)["b",1]
	
	local ll99_winner_`var' = r(table)["ll",3]
	local ul99_winner_`var'  = r(table)["ul",3]
	
	local ll99_loser_`var' = r(table)["ll",2]
	local ul99_loser_`var'  = r(table)["ul",2]

	local ll99_nonvoter_`var' = r(table)["ll",1]
	local ul99_nonvoter_`var'  = r(table)["ul",1]
	
	quietly: margins winner_3, level(95)
	local ll95_winner_`var' = r(table)["ll",3]
	local ul95_winner_`var'  = r(table)["ul",3]
	
	local ll95_loser_`var' = r(table)["ll",2]
	local ul95_loser_`var'  = r(table)["ul",2]
	
	local ll95_nonvoter_`var' = r(table)["ll",1]
	local ul95_nonvoter_`var'  = r(table)["ul",1]
}

* Plot elements
matrix point_winners_noc = `point_winner_SWD', `point_winner_majority_will', `point_winner_strong_leader'
matrix point_losers_noc = `point_loser_SWD', `point_loser_majority_will', `point_loser_strong_leader'
matrix point_nonvoters_noc = `point_nonvoter_SWD', `point_nonvoter_majority_will', `point_nonvoter_strong_leader'

matrix ci_SWD_winner = `ll99_winner_SWD' \ `ul99_winner_SWD' \ `ll95_winner_SWD' \ `ul95_winner_SWD'
matrix ci_majority_will_winner = `ll99_winner_majority_will' \ `ul99_winner_majority_will' \ `ll95_winner_majority_will' \ `ul95_winner_majority_will'
matrix ci_strong_leader_winner = `ll99_winner_strong_leader' \ `ul99_winner_strong_leader' \ `ll95_winner_strong_leader' \ `ul95_winner_strong_leader'

matrix ci_SWD_loser = `ll99_loser_SWD' \ `ul99_loser_SWD' \ `ll95_loser_SWD' \ `ul95_loser_SWD'
matrix ci_majority_will_loser = `ll99_loser_majority_will' \ `ul99_loser_majority_will' \ `ll95_loser_majority_will' \ `ul95_loser_majority_will'
matrix ci_strong_leader_loser = `ll99_loser_strong_leader' \ `ul99_loser_strong_leader' \ `ll95_loser_strong_leader' \ `ul95_loser_strong_leader'

matrix ci_SWD_nonvoter = `ll99_nonvoter_SWD' \ `ul99_nonvoter_SWD' \ `ll95_nonvoter_SWD' \ `ul95_nonvoter_SWD'
matrix ci_majority_will_nonvoter = `ll99_nonvoter_majority_will' \ `ul99_nonvoter_majority_will' \ `ll95_nonvoter_majority_will' \ `ul95_nonvoter_majority_will'
matrix ci_strong_leader_nonvoter = `ll99_nonvoter_strong_leader' \ `ul99_nonvoter_strong_leader' \ `ll95_nonvoter_strong_leader' \ `ul95_nonvoter_strong_leader'

matrix ci_winner_noc = ci_SWD_winner, ci_majority_will_winner, ci_strong_leader_winner
matrix ci_loser_noc = ci_SWD_loser, ci_majority_will_loser, ci_strong_leader_loser
matrix ci_nonvoters_noc = ci_SWD_nonvoter, ci_majority_will_nonvoter, ci_strong_leader_nonvoter

* Controlling for party size 
foreach var of varlist SWD majority_will strong_leader{
	reg `var' i.winner_3 vote_share_party_voted_1 age i.E2002 E2003 extremity E3001 i.cntry_election_num
	est store M_`var'
	estadd local ctryRI "\Checkmark"
	
	margins winner_3, level(99)
	local point_winner_`var' = r(table)["b",2]
	local point_loser_`var' = r(table)["b",1]
	
	local ll99_winner_`var' = r(table)["ll",2]
	local ul99_winner_`var'  = r(table)["ul",2]
	
	local ll99_loser_`var' = r(table)["ll",1]
	local ul99_loser_`var'  = r(table)["ul",1]

	
	quietly: margins winner_3, level(95)
	local ll95_winner_`var' = r(table)["ll",2]
	local ul95_winner_`var'  = r(table)["ul",2]
	
	local ll95_loser_`var' = r(table)["ll",1]
	local ul95_loser_`var'  = r(table)["ul",1]
}


matrix point_winners_con = `point_winner_SWD', `point_winner_majority_will', `point_winner_strong_leader'
matrix point_losers_con = `point_loser_SWD', `point_loser_majority_will', `point_loser_strong_leader'

matrix ci_SWD_winner = `ll99_winner_SWD' \ `ul99_winner_SWD' \ `ll95_winner_SWD' \ `ul95_winner_SWD'
matrix ci_majority_will_winner = `ll99_winner_majority_will' \ `ul99_winner_majority_will' \ `ll95_winner_majority_will' \ `ul95_winner_majority_will'
matrix ci_strong_leader_winner = `ll99_winner_strong_leader' \ `ul99_winner_strong_leader' \ `ll95_winner_strong_leader' \ `ul95_winner_strong_leader'

matrix ci_SWD_loser = `ll99_loser_SWD' \ `ul99_loser_SWD' \ `ll95_loser_SWD' \ `ul95_loser_SWD'
matrix ci_majority_will_loser = `ll99_loser_majority_will' \ `ul99_loser_majority_will' \ `ll95_loser_majority_will' \ `ul95_loser_majority_will'
matrix ci_strong_leader_loser = `ll99_loser_strong_leader' \ `ul99_loser_strong_leader' \ `ll95_loser_strong_leader' \ `ul95_loser_strong_leader'

matrix ci_winner_con = ci_SWD_winner, ci_majority_will_winner, ci_strong_leader_winner
matrix ci_loser_con = ci_SWD_loser, ci_majority_will_loser, ci_strong_leader_loser

matrix colnames point_winners_noc = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames point_losers_noc = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames point_nonvoters_noc = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames point_winners_con = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames point_losers_con = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"

*************
* FIGURE B10: Winner-loser gap in satisfaction with democracy and support for norms of democratic restraint and consent with non-voters
*************

coefplot	(matrix(point_winners_noc), msymbol(S) label("Winners no party size control")  ci((ci_winner_noc[1] ci_winner_noc[2]) (ci_winner_noc[3] ci_winner_noc[4]))) 	///
			(matrix(point_losers_noc), label("Losers no party size control")  ci((ci_loser_noc[1] ci_loser_noc[2]) (ci_loser_noc[3] ci_loser_noc[4])))	///
			(matrix(point_nonvoters_noc), label("Non-voters no party size control")  ci((ci_nonvoters_noc[1] ci_nonvoters_noc[2]) (ci_nonvoters_noc[3] ci_nonvoters_noc[4])))	///
			(matrix(point_winners_con), msymbol(S) label("Winners controlling party size")  ci((ci_winner_con[1] ci_winner_con[2]) (ci_winner_con[3] ci_winner_con[4])))	///
			(matrix(point_losers_con), label("Losers controlling party size")  ci((ci_loser_con[1] ci_loser_con[2]) (ci_loser_con[3] ci_loser_con[4]))),	///		
			coeflabels(,wrap(15)) xlabel(2.6(.2)3.6) ///
			mlabel format(%9.3g) mlabposition(12) mlabgap(*1.5) mlabsize(vsmall)	

graph export "${output}Figure_B10.pdf", replace
	
***********
* TABLE B6: Winner-loser gap in satisfaction with democracy and support for norms of democratic restraint and consent with non-voters
***********
	
	esttab 			M_SWD_noc M_SWD M_majority_will_noc M_majority_will ///			
					M_strong_leader_noc M_strong_leader ///
					using "${output}Table_B6.tex", ///
					b(2) se(2) r2 star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					drop(*.cntry_election_num) ///
					mtitles("SWD" "SWD" "Majority" "Majority"  "Leader" "Leader") ///
					scalars("ctryRI Country-election fixed-effects") nogap


****************					
**** Analysis restricted to those who know who the incubent is/will be, based on official government formation
****************
* Without controlling for party size
foreach var of varlist SWD majority_will strong_leader{
	reg `var' i.winner_bi age i.E2002 E2003 extremity E3001 i.cntry_election_num if incumbent_known==1
	est store M_`var'_noc
	estadd local ctryRI "\Checkmark"
	margins winner_bi, level(99)
	local point_winner_`var' = r(table)["b",2]
	local point_loser_`var' = r(table)["b",1]
	local ll99_winner_`var' = r(table)["ll",2]
	local ul99_winner_`var'  = r(table)["ul",2]
	local ll99_loser_`var' = r(table)["ll",1]
	local ul99_loser_`var'  = r(table)["ul",1]
	quietly: margins winner_bi, level(95)
	local ll95_winner_`var' = r(table)["ll",2]
	local ul95_winner_`var'  = r(table)["ul",2]
	local ll95_loser_`var' = r(table)["ll",1]
	local ul95_loser_`var'  = r(table)["ul",1]
}

* Plot elements
matrix point_winners_noc = `point_winner_SWD', `point_winner_majority_will', `point_winner_strong_leader'
matrix point_losers_noc = `point_loser_SWD', `point_loser_majority_will', `point_loser_strong_leader'

matrix ci_SWD_winner = `ll99_winner_SWD' \ `ul99_winner_SWD' \ `ll95_winner_SWD' \ `ul95_winner_SWD'
matrix ci_majority_will_winner = `ll99_winner_majority_will' \ `ul99_winner_majority_will' \ `ll95_winner_majority_will' \ `ul95_winner_majority_will'
matrix ci_strong_leader_winner = `ll99_winner_strong_leader' \ `ul99_winner_strong_leader' \ `ll95_winner_strong_leader' \ `ul95_winner_strong_leader'

matrix ci_SWD_loser = `ll99_loser_SWD' \ `ul99_loser_SWD' \ `ll95_loser_SWD' \ `ul95_loser_SWD'
matrix ci_majority_will_loser = `ll99_loser_majority_will' \ `ul99_loser_majority_will' \ `ll95_loser_majority_will' \ `ul95_loser_majority_will'
matrix ci_strong_leader_loser = `ll99_loser_strong_leader' \ `ul99_loser_strong_leader' \ `ll95_loser_strong_leader' \ `ul95_loser_strong_leader'

matrix ci_winner_noc = ci_SWD_winner, ci_majority_will_winner, ci_strong_leader_winner
matrix ci_loser_noc = ci_SWD_loser, ci_majority_will_loser, ci_strong_leader_loser

* Controlling for party size 
foreach var of varlist SWD majority_will strong_leader{
	reg `var' i.winner_bi vote_share_party_voted_1 age i.E2002 E2003 extremity E3001 i.cntry_election_num if incumbent_known==1
	est store M_`var'
	estadd local ctryRI "\Checkmark"
	margins winner_bi, level(99)
	local point_winner_`var' = r(table)["b",2]
	local point_loser_`var' = r(table)["b",1]
	local ll99_winner_`var' = r(table)["ll",2]
	local ul99_winner_`var'  = r(table)["ul",2]
	local ll99_loser_`var' = r(table)["ll",1]
	local ul99_loser_`var'  = r(table)["ul",1]
	quietly: margins winner_bi, level(95)
	local ll95_winner_`var' = r(table)["ll",2]
	local ul95_winner_`var'  = r(table)["ul",2]
	local ll95_loser_`var' = r(table)["ll",1]
	local ul95_loser_`var'  = r(table)["ul",1]
}

matrix point_winners_con = `point_winner_SWD', `point_winner_majority_will', `point_winner_strong_leader'
matrix point_losers_con = `point_loser_SWD', `point_loser_majority_will', `point_loser_strong_leader'

matrix ci_SWD_winner = `ll99_winner_SWD' \ `ul99_winner_SWD' \ `ll95_winner_SWD' \ `ul95_winner_SWD'
matrix ci_majority_will_winner = `ll99_winner_majority_will' \ `ul99_winner_majority_will' \ `ll95_winner_majority_will' \ `ul95_winner_majority_will'
matrix ci_strong_leader_winner = `ll99_winner_strong_leader' \ `ul99_winner_strong_leader' \ `ll95_winner_strong_leader' \ `ul95_winner_strong_leader'

matrix ci_SWD_loser = `ll99_loser_SWD' \ `ul99_loser_SWD' \ `ll95_loser_SWD' \ `ul95_loser_SWD'
matrix ci_majority_will_loser = `ll99_loser_majority_will' \ `ul99_loser_majority_will' \ `ll95_loser_majority_will' \ `ul95_loser_majority_will'
matrix ci_strong_leader_loser = `ll99_loser_strong_leader' \ `ul99_loser_strong_leader' \ `ll95_loser_strong_leader' \ `ul95_loser_strong_leader'

matrix ci_winner_con = ci_SWD_winner, ci_majority_will_winner, ci_strong_leader_winner
matrix ci_loser_con = ci_SWD_loser, ci_majority_will_loser, ci_strong_leader_loser

matrix colnames point_winners_noc = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames point_losers_noc = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames point_winners_con = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames point_losers_con = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"

*************
* FIGURE B11: Winner-loser gap in satisfaction with democracy and support for norms of democratic restraint and consent only for cases when the government has been officially formed
************* 

coefplot	(matrix(point_winners_noc), msymbol(S) label("Winners no party size control")  ci((ci_winner_noc[1] ci_winner_noc[2]) (ci_winner_noc[3] ci_winner_noc[4]))) 	///
			(matrix(point_losers_noc), label("Losers no party size control")  ci((ci_loser_noc[1] ci_loser_noc[2]) (ci_loser_noc[3] ci_loser_noc[4])))	///
			(matrix(point_winners_con), msymbol(S) label("Winners controlling party size")  ci((ci_winner_con[1] ci_winner_con[2]) (ci_winner_con[3] ci_winner_con[4])))	///
			(matrix(point_losers_con), label("Losers controlling party size")  ci((ci_loser_con[1] ci_loser_con[2]) (ci_loser_con[3] ci_loser_con[4]))),	///			
			coeflabels(,wrap(15)) xlabel(2.6(.2)3.6) ///
			mlabel format(%9.3g) mlabposition(12) mlabgap(*1.5) mlabsize(vsmall)

graph export "${output}Figure_B11.pdf", replace 

***********
* TABLE B7: Robustness post-coalition I
***********
	esttab 			M_SWD_noc M_SWD M_majority_will_noc M_majority_will M_strong_leader_noc M_strong_leader ///		
					using "${output}Table_B7.tex", ///
					b(2) se(2) r2 star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					drop(*.cntry_election_num) ///
					mtitles("SWD" "SWD" "Majority" "Majority" "Leader" "Leader") ///
					scalars("ctryRI Country-election fixed-effects") nogap

					
****************					
**** Analysis of Strategic winners
****************
					
* Controlling for party size 
foreach var of varlist SWD majority_will strong_leader{
	reg `var' i.winner_strategic vote_share_party_voted_1 age i.E2002 E2003 extremity E3001 i.cntry_election_num
	est store M_`var'
	estadd local ctryRI "\Checkmark"
	
	margins winner_strategic, level(99)
	local point_winner_`var' = r(table)["b",3]
	local point_loser_`var' = r(table)["b",2]
	local point_strategic_`var' = r(table)["b",1]
	
	local ll99_winner_`var' = r(table)["ll",3]
	local ul99_winner_`var'  = r(table)["ul",3]
	
	local ll99_loser_`var' = r(table)["ll",2]
	local ul99_loser_`var'  = r(table)["ul",2]

	local ll99_strategic_`var' = r(table)["ll",1]
	local ul99_strategic_`var'  = r(table)["ul",1]
	
	quietly: margins winner_strategic, level(95)
	local ll95_winner_`var' = r(table)["ll",3]
	local ul95_winner_`var'  = r(table)["ul",3]
	
	local ll95_loser_`var' = r(table)["ll",2]
	local ul95_loser_`var'  = r(table)["ul",2]
	
	local ll95_strategic_`var' = r(table)["ll",1]
	local ul95_strategic_`var'  = r(table)["ul",1]
}


matrix point_winners_con = `point_winner_SWD', `point_winner_majority_will', `point_winner_strong_leader'
matrix point_losers_con = `point_loser_SWD', `point_loser_majority_will', `point_loser_strong_leader'
matrix point_strategic_con = `point_strategic_SWD', `point_strategic_majority_will', `point_strategic_strong_leader'

matrix ci_SWD_winner = `ll99_winner_SWD' \ `ul99_winner_SWD' \ `ll95_winner_SWD' \ `ul95_winner_SWD'
matrix ci_majority_will_winner = `ll99_winner_majority_will' \ `ul99_winner_majority_will' \ `ll95_winner_majority_will' \ `ul95_winner_majority_will'
matrix ci_strong_leader_winner = `ll99_winner_strong_leader' \ `ul99_winner_strong_leader' \ `ll95_winner_strong_leader' \ `ul95_winner_strong_leader'

matrix ci_SWD_loser = `ll99_loser_SWD' \ `ul99_loser_SWD' \ `ll95_loser_SWD' \ `ul95_loser_SWD'
matrix ci_majority_will_loser = `ll99_loser_majority_will' \ `ul99_loser_majority_will' \ `ll95_loser_majority_will' \ `ul95_loser_majority_will'
matrix ci_strong_leader_loser = `ll99_loser_strong_leader' \ `ul99_loser_strong_leader' \ `ll95_loser_strong_leader' \ `ul95_loser_strong_leader'

matrix ci_SWD_strategic = `ll99_strategic_SWD' \ `ul99_strategic_SWD' \ `ll95_strategic_SWD' \ `ul95_strategic_SWD'
matrix ci_majority_will_strategic = `ll99_strategic_majority_will' \ `ul99_strategic_majority_will' \ `ll95_strategic_majority_will' \ `ul95_strategic_majority_will'
matrix ci_strong_leader_strategic = `ll99_strategic_strong_leader' \ `ul99_strategic_strong_leader' \ `ll95_strategic_strong_leader' \ `ul95_strategic_strong_leader'

matrix ci_winner_con = ci_SWD_winner, ci_majority_will_winner, ci_strong_leader_winner
matrix ci_loser_con = ci_SWD_loser, ci_majority_will_loser, ci_strong_leader_loser
matrix ci_strategic_con = ci_SWD_strategic, ci_majority_will_strategic, ci_strong_leader_strategic

matrix colnames point_winners_con = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames point_losers_con = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames point_strategic_con = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"

*****************************
* FIGURE B12: Winner-loser gap in satisfaction with democracy and support for norms of democratic restraint and consent including strategic winners
***************************** 

coefplot	(matrix(point_winners_con), msymbol(S) label("Winners controlling party size")  ci((ci_winner_con[1] ci_winner_con[2]) (ci_winner_con[3] ci_winner_con[4])))	///
			(matrix(point_losers_con), label("Losers controlling party size")  ci((ci_loser_con[1] ci_loser_con[2]) (ci_loser_con[3] ci_loser_con[4])))  ///
			(matrix(point_strategic_con), label("Strategic winners controlling" "party size")  ci((ci_strategic_con[1] ci_strategic_con[2]) (ci_strategic_con[3] ci_strategic_con[4]))),   ///		
			coeflabels(,wrap(15)) xlabel(2.6(.2)3.6) ///
			mlabel format(%9.3g) mlabposition(12) mlabgap(*1.5) mlabsize(vsmall)	

graph export "${output}Figure_B12.pdf", replace 					

***********
* TABLE B8: Strategic winners
***********
	
	esttab 			M_SWD M_majority_will  M_strong_leader ///
					using "${output}Table_B8.tex", ///
					b(2) se(2) r2 star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					drop(*.cntry_election_num) ///
					mtitles("SWD" "Majority" "Leader") ///
					scalars("ctryRI Country-election fixed-effects") nogap	
					
									
****************					
**** Alternative specifications: Multilevel/hierarchical models
****************

* Without controlling for party size:
foreach var of varlist SWD majority_will strong_leader{
	mixed `var' i.winner_bi age i.E2002 E2003 extremity E3001 || cntry_election_num:, reml dfmethod(satterthwaite)					
	est store ML_`var'_noc
	estadd local ctryRI "\Checkmark"
}

* Controlling for party size:
foreach var of varlist SWD majority_will strong_leader{
	mixed `var' i.winner_bi vote_share_party_voted_1 age i.E2002 E2003 extremity E3001 || cntry_election_num:, reml dfmethod(satterthwaite)	
	est store ML_`var'
	estadd local ctryRI "\Checkmark"
}

***********
* TABLE B9: Summary table multilevel models.
***********
esttab 				ML_SWD_noc ML_SWD ML_majority_will_noc ML_majority_will ///
					ML_strong_leader_noc ML_strong_leader ///			
					using "${output}Table_B9.tex", ///
					b(2) se(2) r2 star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					mtitles("SWD" "SWD" "Majority" "Majority" "Leader" "Leader") ///
					nogap
					

* Interaction with polarization:
foreach var of varlist SWD majority_will strong_leader{
	mixed `var' i.winner_bi##c.distance age i.E2002 E2003 extremity E3001 || cntry_election_num:, reml dfmethod(satterthwaite)	
	est store ML_APO_`var'

}					
					
foreach var of varlist SWD majority_will strong_leader{
	mixed `var' i.winner_bi##c.distance vote_share_party_voted_1 age i.E2002 E2003 extremity E3001 || cntry_election_num:, reml dfmethod(satterthwaite)	
	est store ML_APO_`var'_pars

}

************
* TABLE B10: Interaction with affective polarization: multilevel specification
************
	esttab 			ML_APO_SWD ML_APO_SWD_pars ML_APO_majority_will ML_APO_majority_will_pars ML_APO_strong_leader ML_APO_strong_leader_pars ///		
					using "${output}Table_B10.tex", ///
					b(2) se(2) star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels nodiscrete ///
					mtitles("SWD" "SWD" "Majority" "Majority" "Leader" "Leader") ///
					nogap
						
****************	
** Subgroup analyses (based on the multilevel especification):
****************

** Merge dataset with country-election-level variables
merge m:1 E1004 using "${working}ert.dta"


************
* TABLE B11: List of Countries and Country-election level Variables 
************

preserve

label var E1004          "Election"
label var v2x_polyarchy  "Polyarchy"
label var aut_ep         "Backsliding"
label var system         "System"



* ==== 1) Ensure variables are in place and compute N obs per election ====
* If `system` is numeric with value labels, decode to string
* ==== 1) Prepare variables ====
capture confirm string variable system
if _rc {
    decode system, gen(system_str)
    drop system
    rename system_str system
}

bys E1004: gen N = _N
bys E1004: keep if _n == 1
order E1004 v2x_polyarchy aut_ep system N
sort E1004
format v2x_polyarchy %6.3f
format aut_ep        %1.0f
format N             %9.0fc

* ==== 2) Write LaTeX table ====
tempname fh
local outfile "${output}Table_B11.tex"
file close _all
file open `fh' using "`outfile'", write replace text

file write `fh' "% Auto-generated by Stata" _n
file write `fh' "\begin{table}[!ht]" _n
file write `fh' "\centering" _n
file write `fh' "\singlespace" _n
file write `fh' "\scriptsize" _n   // <<-- set smaller font size
file write `fh' "\begin{tabular}{l c c c r}" _n
file write `fh' "\toprule" _n
file write `fh' "Election & Polyarchy & Backsliding & System & N obs \\\\" _n
file write `fh' "\midrule" _n

quietly {
    forvalues i = 1/`=_N' {
        * Escape underscores in the Election variable for LaTeX
        local el = subinstr(E1004[`i'], "_", "\_", .)
        local pol  : display %6.3f v2x_polyarchy[`i']
        local back : display %1.0f aut_ep[`i']
        local sys  : display system[`i']
        local nobs : display %9.0fc N[`i']

        file write `fh' "`el' & `pol' & `back' & `sys' & `nobs' \\\\" _n
    }
}

file write `fh' "\bottomrule" _n
file write `fh' "\end{tabular}" _n
file write `fh' "\caption{Elections in the sample}" _n
file write `fh' "\label{tab:elections}" _n
file write `fh' "\end{table}" _n
file close `fh'

display as txt "Wrote LaTeX table to: `outfile'"

restore

	

*** Hetereogeneous effects by political system (presidential vs parliamentary)

fre system // we use this variable that was created previously

* Main models (with and without party size)
foreach var of varlist SWD majority_will strong_leader{
	mixed `var' i.winner_bi##i.system vote_share_party_voted_1 age i.E2002 E2003 extremity E3001 || cntry_election_num: winner_bi, reml dfmethod(satterthwaite)	
	est store ML_S_`var'
	
	mixed `var' i.winner_bi##i.system age i.E2002 E2003 extremity E3001 || cntry_election_num: winner_bi, reml dfmethod(satterthwaite)	
	est store ML_S_`var'_nop
}

************
* TABLE B12: Robustness presidential-parliamentary
************
esttab 				ML_S_SWD ML_S_SWD_nop ML_S_majority_will ML_S_majority_will_nop ML_S_strong_leader ML_S_strong_leader_nop ///
					using "${output}Table_B12.tex", ///
					b(2) se(2) star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					mtitles("SWD" "SWD" "Majority" "Majority" "Leader" "Leader") ///
					nogap


*** Heterogeneous effects by democratic quality (V-Dem polyarchy index):	

foreach var of varlist SWD majority_will strong_leader{
	mixed `var' i.winner_bi##c.v2x_polyarchy vote_share_party_voted_1 age i.E2002 E2003 extremity E3001 || cntry_election_num: winner_bi, reml dfmethod(satterthwaite)	
	est store ML_`var'_demqual

}

************
* TABLE B13: Robustness democratic quality
************
	esttab 			ML_SWD_demqual ML_majority_will_demqual ML_strong_leader_demqual ///			
					using "${output}Table_B13.tex", ///
					b(2) se(2) star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					mtitles("SWD" "Majority" "Leader") ///
					nogap

					
*** Hetereogeneous effects by whether the country is experiencing democratic backsliding or not:

foreach var of varlist SWD majority_will strong_leader{
	mixed `var' i.winner_bi##i.aut_ep vote_share_party_voted_1 age i.E2002 E2003 extremity E3001 || cntry_election_num: winner_bi, reml dfmethod(satterthwaite)	
	est store ML_`var'_back

}

************
* TABLE B14: Multilevel heterogeneous effects: backsliding cases
************
	esttab 			ML_SWD_back ML_majority_will_back ML_strong_leader_back ///			
					using "${output}Table_B14.tex", ///
					b(2) se(2) star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					mtitles("SWD" "Majority" "Leader") ///
					nogap

					
*++++++++++++++++++++++++++++++++ STUDY 2 +++++++++++++++++++++++++++++++++++++*
					
*+++++++++++++++++++++++++ DATA MANAGEMENT STUDY 2 ++++++++++++++++++++++++++++* 
 

use "${working}nz2017.dta", clear

* create winner and winner_bi (just in case we want to replicate previous analyses)
replace winner=.
replace winner=2 if respondent_vote == "554001" & inter_date <= mdy(10, 19, 2017)
replace winner=0 if respondent_vote == "554001" & inter_date > mdy(10, 19, 2017)

replace winner=0 if respondent_vote=="554002" & inter_date <= mdy(10, 19, 2017)
replace winner=2 if respondent_vote=="554002" & inter_date > mdy(10, 19, 2017)

replace winner=0 if respondent_vote=="554003" & inter_date <= mdy(10, 19, 2017)
replace winner=1 if respondent_vote=="554003" & inter_date > mdy(10, 19, 2017)

foreach party in "554004" "554005" "554006" "554007" "554008" "554009" "554010" "554011" "554012" "554013" "554014" "554015" "554016"{
replace winner=0 if respondent_vote=="`party'"
}

replace winner_bi=0 if winner==0
replace winner_bi=1 if winner==1
replace winner_bi=1 if winner==2
tab winner_bi winner

* Dependent variables (some are not coded in the working dataset for NZ)
replace E3023=. if E3023>=8
gen SWD = E3023
recode SWD 5=1 4 =2 6=3 2=4 1=5
replace SWD=. if SWD>=7
label val SWD satisfaction

gen strong_leader = E3004_5 if E3004_5<7
replace strong_leader = 6 - strong_leader
label val strong_leader likert_rev

* Announcement date and treated group (labour only) and non-treated(only National Party)

gen treatment=1 if respondent_vote=="554002" & E3013_LH_DC!= 999998 & E3013_LH_DC!= 999999
replace treatment=0 if respondent_vote!="554002" & E3013_LH_DC!= 999998 & E3013_LH_DC!= 999999

gen after = 1 if inter_date > mdy(10, 19, 2017)
replace after=0 if inter_date <= mdy(10, 19, 2017)

* Variable labels
label var treatment "Labor voter"
label var treatment "After announcement"
label var SWD "Satisfaction with democracy"
label var majority_will "Majoritarianism vs Minorities"
label var strong_leader "Strong leader bends rules"
label var winner_bi "Winner"
label var age "Age"
label var E2002 "Female"
label var E2003 "Education"
label var extremity "Ideological extremity"
label var vote_share_party_voted_1 "Vote share party voted"
label var distance "Affective polarization"
label var average_dislike2 "Rival resentment"
label var E3020 "Ideology"
label var E3003 "I. Efficacy"
label var E3001 "Political interest"
label def sex 1"Male" 2"Female"
label val E2002 sex

label def treatment 1"Labor" 0"National"
label val treatment treatment

label def after 1"After announcement" 0"Before announcement"
label val after after

*+++++++++++++++++++++++++++++ ANALYSIS STUDY 2 +++++++++++++++++++++++++++++++* 

***********
* Table C1: Impact of coalition announcement on political support
***********
local x 0
foreach var of varlist SWD majority_will strong_leader{
	local ++ x
	reg `var' i.treatment##i.after age i.E2002 E2003
	est store M`x'
}

esttab 				M1 M2 M3 using "${output}Table_C1.tex", ///
					b(2) se(2) r2 star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					mtitles("SWD" "Majority" "Leader") ///
					nogap 

************
* FIGURE C1: Change in gaps in SWD and norms of restraint and consent between voters of Labour and National parties
************  
matrix point = J(1,3,.)
matrix CI = J(4,3,.)

local x 0
foreach var of varlist SWD majority_will strong_leader{
	local ++ x
	reg `var' i.treatment##i.after age i.E2002 E2003
	margins r.after, dydx(treatment) level(95)
	matrix point[1,`x'] = r(table)[1,2]
	matrix CI[1,`x'] = r(table)[5..6,2]
	margins r.after, dydx(treatment) level(99)
	matrix CI[3,`x'] = r(table)[5..6,2]
}

matrix colnames point = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
matrix colnames CI = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"

coefplot	(matrix(point), ci((CI[3] CI[4]) (CI[1] CI[2]))), 	///		
			mlabel format(%9.3g) mlabposition(12) mlabgap(*1.5) mlabsize(vsmall) xline(0, lcol(red) lpat(solid))	///
			xtitle("Change in gap between Labour and National after announcement")
			
graph export "${output}Figure_C1.pdf", replace 

************
* FIGURE C2: Predicted value of outcome variables among voters of Labour and National parties
************

matrix point_lab_before = J(1,3,.)
matrix point_lab_after = J(1,3,.)
matrix point_nat_before = J(1,3,.)
matrix point_nat_after = J(1,3,.)
matrix CI_lab_before = J(4,3,.)
matrix CI_lab_after = J(4,3,.)
matrix CI_nat_before = J(4,3,.)
matrix CI_nat_after = J(4,3,.)

local x 0
foreach var of varlist SWD majority_will strong_leader{
	local ++ x
	reg `var' i.treatment##i.after age i.E2002 E2003
	margins treatment, at(after=(0 1)) 
	matrix point_lab_before[1,`x'] = r(table)[1,2]
	matrix point_lab_after[1,`x'] = r(table)[1,4]
	matrix point_nat_before[1,`x'] = r(table)[1,1]
	matrix point_nat_after[1,`x'] = r(table)[1,3]
	matrix CI_lab_before[1,`x'] = r(table)[5..6,2]
	matrix CI_lab_after[1,`x'] = r(table)[5..6,4]
	matrix CI_nat_before[1,`x'] = r(table)[5..6,1]
	matrix CI_nat_after[1,`x'] = r(table)[5..6,3]
	margins treatment, at(after=(0 1)) level(99)
	matrix CI_lab_before[3,`x'] = r(table)[5..6,2]
	matrix CI_lab_after[3,`x'] = r(table)[5..6,4]
	matrix CI_nat_before[3,`x'] = r(table)[5..6,1]
	matrix CI_nat_after[3,`x'] = r(table)[5..6,3]
}

foreach x in lab_before lab_after nat_before nat_after{
	matrix colnames point_`x' = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
	matrix colnames CI_`x' = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
}

coefplot	(matrix(point_lab_before), label("Before announcement")  ci((CI_lab_before[3] CI_lab_before[4]) (CI_lab_before[1] CI_lab_before[2]))) 	///
			(matrix(point_lab_after), label("After announcement")  ci((CI_lab_after[3] CI_lab_after[4]) (CI_lab_after[1] CI_lab_after[2]))), bylabel("Labour voters")	///
			||  (matrix(point_nat_before), label("Before announcement")  ci((CI_nat_before[3] CI_nat_before[4]) (CI_nat_before[1] CI_nat_before[2])))	///
			(matrix(point_nat_after), label("After announcement")  ci((CI_nat_after[3] CI_nat_after[4]) (CI_nat_after[1] CI_nat_after[2]))), bylabel("National voters")	///			
			coeflabels(,wrap(15)) xlabel(2(.2)3.8) ///
			mlabel format(%9.3g) mlabposition(12) mlabgap(*1.5) mlabsize(vsmall)	
					
graph export "${output}Figure_C2.pdf", replace 


************
* FIGURE 3: Effect of coalition announcement on SWD and norms of democratic restraint and consent among voters of the Labour and National
************
matrix point_lab = J(1,3,.)
matrix point_nat = J(1,3,.)
matrix CI_lab = J(4,3,.)
matrix CI_nat = J(4,3,.)

local x 0
foreach var of varlist SWD majority_will strong_leader{
	local ++ x
	reg `var' i.treatment##i.after age i.E2002 E2003
	margins treatment, dydx(after)
	matrix point_lab[1,`x'] = r(table)[1,4]
	matrix point_nat[1,`x'] = r(table)[1,3]
	matrix CI_lab[1,`x'] = r(table)[5..6,4]
	matrix CI_nat[1,`x'] = r(table)[5..6,3]
	margins treatment, dydx(after) level(99)
	matrix CI_lab[3,`x'] = r(table)[5..6,4]
	matrix CI_nat[3,`x'] = r(table)[5..6,3]
}

foreach x in lab nat{
	matrix colnames point_`x' = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
	matrix colnames CI_`x' = "Satisfaction with democracy" "Majoritarianism vs Minorities" "Strong leader bends rules"
}

coefplot	(matrix(point_lab), label("Labour Voters")  ci((CI_lab[3] CI_lab[4]) (CI_lab[1] CI_lab[2]))) 	///
			(matrix(point_nat), label("National Voters")  ci((CI_nat[3] CI_nat[4]) (CI_nat[1] CI_nat[2]))), bylabel("Labour voters")	///	
			coeflabels(,wrap(15)) ///
			mlabel format(%9.3g) mlabposition(12) mlabgap(*1.5) mlabsize(vsmall) xline(0, lpattern(solid))	///
			xtitle("Impact of coalition agreement anouncement")
			
			
graph export "${output}Figure_3.pdf", replace



*++++++++++++++++++++++++++++++++  STUDY 3 ++++++++++++++++++++++++++++++++++++*

*+++++++++++++++++++++++++ DATA MANAGEMENT STUDY 3 ++++++++++++++++++++++++++++*

* Load new dataset 
use "${data}TRI_POL_CH_endTimeW2.dta", clear

* Recoding variables
recode p5g_2 1=4 2=3 3=2 4=1, gen(majority_will)
la def majority_will_l 1 "Not important" 2 "Somewhat important" 3 "Important" 4 "Very important" 
la val majority_will majority_will_l


recode p5f_2 1=4 2=3 3=2 4=1, gen(minority_rights)
la def minority_rights_l 1 "Not important" 2 "Somewhat important" 3 "Important" 4 "Very important" 
la val minority_rights minority_rights_l

recode p7b_2 1=4 2=3 3=2 4=1, gen(strong_leader)
la def strong_leader_l 1 "Not important" 2 "Somewhat important" 3 "Important" 4 "Very important" 
la val strong_leader strong_leader_l


* Coding of winners and losers
gen winner = 1 if p41a_CH_2 == 1 | p41b_CH_2 == 1 
replace winner = 0 if p41a_CH_2 == 2 | p41b_CH_2 == 2


*Code interview day: before/after elections
gen after = 1 if endTimeW2 > mdy(12, 19, 2021)
replace after = 0 if endTimeW2 <= mdy(12, 19, 2021)
replace after =. if endTimeW2==.
label var after "After announcement"
label define after 1"After announcement" 0"Before announcement"
label val after after


* Relabel variables for plots
label var p19b_CH_2 "Trust in government"
label var majority_will "Majoritarian rule"
label var minority_rights "Protection of minority rights"
label var strong_leader "Strong leader running country without National Assembly"
label def winner 1"Boric voters" 0"Kast voters"
label val winner winner 
label var s4b_CH_1 "Education"
label var WAPDV_1 "Affective polarization (Wagner's distance measure)"
label var p1_1 "Political interest"

*++++++++++++++++++++++++++++ ANALYSIS STUDY 3 ++++++++++++++++++++++++++++++++*

* Defining matrices to store results
matrix results_winners = J(5,4,.) // Defining matrix to store results 
matrix results_losers = J(5,4,.) // Defining matrix to store results 
matrix colnames results_winners  = "p19b_CH_2" "majority_will" "minority_rights" "strong_leader"
matrix rownames results_winners = "estimate" "ll95" "ul95" "ll99" "ul99"
matrix colnames results_losers  = "p19b_CH_2" "majority_will" "minority_rights" "strong_leader"
matrix rownames results_losers = "estimate" "ll95" "ul95" "ll99" "ul99"

* Loop over the variables and storing results to be plotted in matrices 

local col 0 // Local for possition in matrix in loop 

foreach var of varlist p19b_CH_2 majority_will minority_rights strong_leader{
	local ++ col 
	
	reg `var' i.winner##i.after s1_2 s2_2 c.s4b_CH_1 p1_1
	margins winner, dydx(after) post level (95)
	
	matrix results_winners[1,`col'] = r(table)[1,4] \ r(table)[5,4] \ r(table)[6,4]
	matrix results_losers[1,`col'] = r(table)[1,3] \ r(table)[5,3] \ r(table)[6,3]
	
	reg `var' i.winner##i.after s1_2 s2_2 c.s4b_CH_1 p1_1
	margins winner, dydx(after) post level (99)
	
	matrix results_winners[4,`col'] = r(table)[5,4] \ r(table)[6,4]
	matrix results_losers[4,`col'] = r(table)[5,3] \ r(table)[6,3]
}

***********
* FIGURE 4: Main effects Chile
***********
coefplot 	(matrix(results_winners), label("Boric voters")  ci((results_winners[4] results_winners[5]) (results_winners[2] results_winners[3])))	///
			(matrix(results_losers), label("Kast voters")  ci((results_losers[4] results_losers[5]) (results_losers[2] results_losers[3]))), 	///
			xline(0, lpattern(solid)) xtitle("Effect of winning or losing election")	///
			mlabel format(%9.3g) mlabposition(12) mlabgap(*1.5) mlabsize(vsmall) coeflabels(, wrap(20))
			
graph export "${output}Figure_4.pdf", replace

************
** Table D1: Impact of becoming a winner or loser on political supporT
************

local x 0
foreach var of varlist p19b_CH_2 majority_will minority_rights strong_leader{
	local ++ x
	reg `var' i.winner##i.after s1_2 s2_2 c.s4b_CH_1 p1_1
	est store M`x'
}

esttab 				M1 M2 M3 M4 using "${output}Table_D1.tex", ///
					b(2) se(2) r2 star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					mtitles("Trust" "Majority" "Minorities" "Assembly") ///
					nogap 

******* Interaction with affective polarization distance measure (only socio-demographic controls that cannot be considered post-treatment)

gen loser= 1-winner 
label def loser 1"Kast voters" 0"Boric voters"
label val loser loser 

***** We reverse the variable so as to keep consistency in use of colors for winners and losers in Chile and NZ. Otherwise, when doing an interaction, stata changes the color pattern automatically. 


foreach var of varlist p19b_CH_2 majority_will minority_rights strong_leader{	
	
	local label : variable label `var'	
	
	reg `var' i.loser##i.after##c.WAPDV_1 s1_2 s2_2 c.s4b_CH_1 p1_1
	* matrix list r(table)
	local pvalue: di %4.3f el(r(table),4,17)
	
	margins loser, dydx(after) at(WAPDV_1=(0(1)10))
	marginsplot, 	yline(0, lpattern(solid)) ///
					ytitle("Effect of winning or losing election") xtitle("Affective polarization (distance measure)")	ti("`label'") ///
					legend(position(bottom)) ///
					ysize(4) xsize(4) ///
					note("p-value product term = `pvalue'", size(vsmall))
					
	graph save "${aux}`var'.gph", replace
}

***********
* FIGURE 5: Effects of Boric’s victory on trust in government and support for democratic norms as a function of winner-loser status and affective polarization
***********

grc1leg2		"${aux}p19b_CH_2.gph"	///
				"${aux}majority_will.gph"	///
				"${aux}minority_rights.gph"	///
				"${aux}strong_leader.gph", 	///
				lcols(2) xcommon
				
graph export "${output}Figure_5.pdf", replace

***********
* TABLE D2: impact of becoming a winner or loser on political support conditional on affective polarization
***********

label var WAPDV_1 "APO"
local x 0
foreach var of varlist p19b_CH_2 majority_will minority_rights strong_leader{
	local ++ x
	reg `var' i.winner##i.after##c.WAPDV_1 s1_2 s2_2 c.s4b_CH_1 p1_1
	est store M`x'
}

esttab 				M1 M2 M3 M4 using "${output}Table_D2.tex", ///
					b(2) se(2) r2 star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					mtitles("Trust" "Majority" "Minorities" "Assembly") ///
					nogap 

*** APPENDIX STUDY 3: extra plots 
*Predicted values for the 4 outcomes 

matrix point_lab_before = J(1,4,.)
matrix point_lab_after = J(1,4,.)
matrix point_nat_before = J(1,4,.)
matrix point_nat_after = J(1,4,.)
matrix CI_lab_before = J(4,4,.)
matrix CI_lab_after = J(4,4,.)
matrix CI_nat_before = J(4,4,.)
matrix CI_nat_after = J(4,4,.)

local x 0
foreach var of varlist p19b_CH_2 majority_will minority_rights strong_leader{
	local ++ x
	reg `var' i.winner##i.after s1_2 s2_2 c.s4b_CH_1 p1_1
	margins winner, at(after=(0 1)) 
	matrix point_lab_before[1,`x'] = r(table)[1,2]
	matrix point_lab_after[1,`x'] = r(table)[1,4]
	matrix point_nat_before[1,`x'] = r(table)[1,1]
	matrix point_nat_after[1,`x'] = r(table)[1,3]
	matrix CI_lab_before[1,`x'] = r(table)[5..6,2]
	matrix CI_lab_after[1,`x'] = r(table)[5..6,4]
	matrix CI_nat_before[1,`x'] = r(table)[5..6,1]
	matrix CI_nat_after[1,`x'] = r(table)[5..6,3]
	margins winner, at(after=(0 1)) level(99)
	matrix CI_lab_before[3,`x'] = r(table)[5..6,2]
	matrix CI_lab_after[3,`x'] = r(table)[5..6,4]
	matrix CI_nat_before[3,`x'] = r(table)[5..6,1]
	matrix CI_nat_after[3,`x'] = r(table)[5..6,3]
}

foreach x in lab_before lab_after nat_before nat_after{
	matrix colnames point_`x' = "Trust in government" "Majoritarian rule" "Protection of minority rights" "Abolishment national assembly"
	matrix colnames CI_`x' = "Trust in government" "Majoritarian rule" "Protection of minority rights" "Abolishment national assembly"
}

************
* FIGURE D1: Predicted value of outcome variables among Boric and Kast voters
************

coefplot	(matrix(point_lab_before), label("Before announcement")  ci((CI_lab_before[3] CI_lab_before[4]) (CI_lab_before[1] CI_lab_before[2]))) 	///
			(matrix(point_lab_after), label("After announcement")  ci((CI_lab_after[3] CI_lab_after[4]) (CI_lab_after[1] CI_lab_after[2]))), bylabel("Boric voters")	///
			||  (matrix(point_nat_before), label("Before announcement")  ci((CI_nat_before[3] CI_nat_before[4]) (CI_nat_before[1] CI_nat_before[2])))	///
			(matrix(point_nat_after), label("After announcement")  ci((CI_nat_after[3] CI_nat_after[4]) (CI_nat_after[1] CI_nat_after[2]))), bylabel("Kast voters")	///			
			coeflabels(,wrap(15)) xlabel(1.5(.5)4.5) ///
			mlabel format(%9.3g) mlabposition(12) mlabgap(*1.5) mlabsize(vsmall)	
						
graph export "${output}Figure_D1.pdf", replace 

***********
* TABLE D3: Alternative estimation: Affective Polarization spread measure
***********

label var WAPSV_1 "APO"
local x 0
foreach var of varlist p19b_CH_2 majority_will minority_rights strong_leader{
	local ++ x
	reg `var' i.winner##i.after##c.WAPSV_1 s1_2 s2_2 c.s4b_CH_1 p1_1
	est store M`x'
}

esttab 				M1 M2 M3 M4 using "${output}Table_D3.tex", ///
					b(2) se(2) r2 star(* 0.05 ** 0.01)  ///
					nobase label replace interaction(" X ")  ///
					nobaselevels  nodiscrete ///
					mtitles("Trust" "Majority" "Minorities" "Assembly") ///
					nogap 

************
* FIGURE D2: Effects of Boric’s victory on trust in government and support for democratic norms as a function of winner and loser status and affective polarization (spread measure)
************
label var WAPSV_1 "Affective polarization (Wagner's spread measure)"
			
foreach var of varlist p19b_CH_2 majority_will minority_rights strong_leader{	
	
	local label : variable label `var'	
	
	reg `var' i.loser##i.after##c.WAPSV_1 s1_2 s2_2 c.s4b_CH_1 p1_1
	margins loser, dydx(after) at(WAPSV_1=(0(1)5))
	marginsplot, 	yline(0, lpattern(solid)) ///
					ytitle("Effect of winning or losing election") xtitle("Affective polarization (spread measure)")	ti("`label'") ///
					legend(position(bottom)) ///
					 ysize(4) xsize(4)
	graph save "${aux}`var'.gph", replace
}

grc1leg2		"${aux}p19b_CH_2.gph"	///
				"${aux}majority_will.gph"	///
				"${aux}minority_rights.gph"	///
				"${aux}strong_leader.gph", 	///
				lcols(2) xcommon
						
graph export "${output}Figure_D2.pdf", replace			
			







